Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I show my custom user and user in same form and make it work?
I have 2 models: teacher and student. They both extend User class with a OneToOneField and they both have receivers defined for creation and saving. Now, in my forms I can only display the fields from student or teacher only, the other fields that come with user I don't know how to include them. But I want that a student or a teacher won't be able to create account, unless all fields are filled in. Here are my forms and view: class StudentSignUpView(CreateView): model = User form_class = StudentSignUpForm template_name = 'student_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'student' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('index') class TeacherSignUpView(CreateView): model = User form_class = TeacherSignUpForm template_name = 'teacher_signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'teacher' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return render_to_response('index.html', {'form': form},) class StudentSignUpForm(forms.ModelForm): class Meta: model = Student fields = ('student_ID', 'photo', 'phone') class TeacherSignUpForm(forms.ModelForm): class Meta: model = Teacher fields = ('academic_title', 'photo', 'phone', 'website', 'bio') -
Why won't importlib find my module
I'm trying to programmatically import a module. This works: from dirname.models import modelclass as m But this doesn't: import importlib m = importlib.import_module('models.modelclass', package='dirname') I try running this script from the directory that holds dirname. dirname contains a init.py file. I'm trying to make this work using django. I get an ImportError saying "No module named 'models'" -
How can I stop a daemon thread from a view in Django project?
This is my model: class TicketsDeploymentModel(models.Model, threading.Thread): tickets_in_qeue = models.BooleanField() tickets_sent = models.CharField(max_length=20) deployment_error = models.BooleanField() def _create_stop_event(self): self._stop_event = threading.Event() def stop(self): self._stop_event.set() def stopped(self): return self._stop_event.is_set() def _deploy_tickets(self): import smtplib, time, random from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage def create_email_service(): s = smtplib.SMTP(host='smtp.gmail.com', port=587) s.starttls() s.login(USERNAME, PASSWORD) return s self.tickets_in_qeue = True self.tickets_sent = 0 self.deployment_error = False self.save() all_tickets = TicketsModel.objects.filter(ticket_status=True) ticket_emails = [] for counter,ticket in enumerate(all_tickets): ticket_emails.append(MIMEMultipart()) ticket_emails[counter]['From']='chinon19@gmail.com' ticket_emails[counter]['To']='germantestingapp@mailinator.com' ticket_emails[counter]['Subject'] = ticket.ticket_subject ticket_emails[counter].attach(MIMEText(ticket.ticket_body, 'plain')) for counter,ticket in enumerate(ticket_emails): if not self.stopped(): try: service = create_email_service() service.send_message(ticket) self.tickets_sent = '{} out of {}'.format(counter + 1, len(all_tickets)) self.save() print(self.tickets_sent + ' tickets have been sent.') time.sleep(random.randint(5,10)) except KeyboardInterrupt: self.tickets_in_qeue = False self.save() return except: self.deployment_error = True self.tickets_in_qeue = False self.save() return print('An exception occurred: most probably an SMTP connection error.') self.tickets_in_qeue = False self.save() # self.delete() return def deploy_as_daemon(self): deployment = threading.Thread(target = self._deploy_tickets) self._create_stop_event() deployment.daemon = True deployment.start() And I want to stop the daemon thread from one of my views: def DeployTicketsView(request): current_deployment = TicketsDeploymentModel() current_deployment.deploy_as_daemon() return render(request, 'tickets/confirm_tickets_deployment.html', {'current_deployment':current_deployment}) def StopDeploymentView(request, pk): current_deployment = TicketsDeploymentModel.objects.get(pk=pk) current_deployment.stop() return render(request,'tickets/deployment_interrupted.html') The error that I'm getting is in the first … -
django-mssql database error, SQL query error
I am using django-mssql to connect to the database. I am doing a raw sql query to the database but I get this error. django.db.utils.DatabaseError: (-2147352567, 'Exception occurred .', (0, 'Microsoft SQL Server Native Client 11.0', 'Error conver ting data type varchar to bigint.', None, 0, -2147217913), None) Command: SELECT Attribute FROM ML.attribute WHERE CompanyID = '1' AND Att ributeID NOT IN (SELECT AttributeID FROM ML.correlatedattribute WHERE ProductID ='AUTO_LOAN')AND (Useless != 1 OR Useless IS NUL L) The body of function calling the database is like this def query(query_string): cursor = connection.cursor() cursor.execute(query_string) rows = cursor.fetchall() cursor.close() return rows The error seems to be something to do with data type but I have no idea how to solve this. -
What are the most user-friendly methods to create interactive graphics/charts on a webpage?
I'm looking to create a webpage with interactive charts that can be updated on the back-end by a MySQL database. IE. A website that hosts a graph that has points which can be clicked on for additional information. I have a background in Python programming and have started looking over Django documentation but am struggling with following the documentation's tutorial as I progress. Are there other languages, methods or perhaps Django tutorials that anyone can recommend for a project like this? Looking for video material myself hasn't reaped much success. -
Invoke a seperate event when I click on a hyperlink on my Django template page
I have an tag on my Django template for an advert that fulfills two functions: When a user clicks it, data is logged about the click (its location on the page, the text of the link, etc.) It is then redirected to an external link on a different website. The way the page template is loaded is that the tag is dynamically filled with the href attribute pointing towards a view function in my views.py : <a href="url arg1&arg2&redirect_url" target="_blank"> <span dir="ltr">Lawyer Education</span> </a> The problem is that in practice, when a user hovers over my hyperlink, on the bottom left of the browser they see the URL pointing towards the view and its DJango url with arguments is displayed as opposed to the URL they are expecting to be redirected to. Is it possible to have the redirect URL be displayed instead in some way? Or to have the view function be fired as an event while the redirect occurs at the same time? Javascript/jQuery/PHP is not my forte so I am not sure how to proceed if that is the way to go to solve my problem... -
Start Scraping Process in Django App
I recently had a developer work on a project with me for a web application that scrapes news articles and allows assesses them uses NLP. I'm new to Python and have never used Django before, but have managed to get the app up and running on a host. Unfortunately the developer is now unavailable and although the project is almost ready, I'm not exactly sure how to execute the scraping process. It uses the following packages: beautifulsoup4==4.6.0 dj-database-url==0.4.1 Django>=1.9.7 django-allauth==0.32.0 django-filter==1.0.4 django-taggit==0.22.1 djangorestframework==3.6.3 django-taggit-serializer==0.1.5 feedfinder2==0.0.4 feedparser==5.2.1 gunicorn==19.6.0 newspaper3k==0.2.2 nltk==3.2.4 parsedatetime==2.1 psycopg2==2.7.1 virtualenv==15.1.0 whitenoise==2.0.6 oauthlib==2.0.2 requests-oauthlib==0.8.0 django-rest-auth==0.9.1 markdown word2number django-cors-headers Does anyone who knows Django and/or the installed packages know where I might find the scripts if they are there? The repository is available here: https://github.com/davemate23/swendle I have the app and database running locally, so understanding how to start the scraping and NLP/data analysis process would be really helpful. Thanks -
Python coverage parse exception
When I try to send python project with sonar-scaner, it throws me the following exception "Caused by: java.lang.IllegalStateException: Unknown report version: 4.4.2. This parser only handles version 1.". Before trying to introduce the cover, the project was run normally, the project is python code and the report is created with django-nose. More information: sonar version: 6.7.1 sonar scanner command: sonar-scanner -Dsonar.projectKey=nanas -Dsonar.host.url=http://192.168.0.**:9001 -Dsonar.login=8c047********************33c3111b5 sonar doesn't run through a proxy I'm attaching sonar project configuration file and coverage xml file generated by django-nose. I have been reviewing several forums but I can't find a solution to my problem, I would need to solve this problem in order to continue with the automatic code analysis in my project. Best regards, Jose Luis Exception: 12:53:31.919 ERROR: Error during SonarQube Scanner execution Error during parsing of the generic coverage report '/home/bamboo-home/xml-data/build-dir/NAN-CI6-JOB1/xmlrunner/coverage.xml'. Look at SonarQube documentation to know the expected XML format. Caused by: java.lang.IllegalStateException: Unknown report version: 4.4.2. This parser only handles version 1. at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.parseRootNode(GenericCoverageReportParser.java:72) at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.lambda$parse$0(GenericCoverageReportParser.java:64) at org.sonar.api.utils.StaxParser.parse(StaxParser.java:115) at org.sonar.api.utils.StaxParser.parse(StaxParser.java:95) at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.parse(GenericCoverageReportParser.java:65) at org.sonar.scanner.genericcoverage.GenericCoverageReportParser.parse(GenericCoverageReportParser.java:54) at org.sonar.scanner.genericcoverage.GenericCoverageSensor.execute(GenericCoverageSensor.java:109) at org.sonar.scanner.sensor.SensorWrapper.analyse(SensorWrapper.java:53) at org.sonar.scanner.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:88) at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:82) at org.sonar.scanner.phases.SensorsExecutor.execute(SensorsExecutor.java:68) at org.sonar.scanner.phases.AbstractPhaseExecutor.execute(AbstractPhaseExecutor.java:88) at org.sonar.scanner.scan.ModuleScanContainer.doAfterStart(ModuleScanContainer.java:180) at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:135) at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:121) at org.sonar.scanner.scan.ProjectScanContainer.scan(ProjectScanContainer.java:288) at org.sonar.scanner.scan.ProjectScanContainer.scanRecursively(ProjectScanContainer.java:283) at org.sonar.scanner.scan.ProjectScanContainer.doAfterStart(ProjectScanContainer.java:261) at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:135) at org.sonar.core.platform.ComponentContainer.execute(ComponentContainer.java:121) … -
Where is robots.txt coming from (Nginx + Gunicorn + Django)?
I am running a server with Nginx + Gunicorn + Django. I have configured Django to show a robots.txt file, and this works just fine when I test Django on its own, without Nginx+Gunicorn. However, when I run the whole stack, /robots.txt suddenly gets replaced with a different file that I didn't write. Why is this happening? I never wrote anything to tell Nginx or Gunicorn to do such a thing. Is there a default somewhere that I need to overwrite or deactivate? The folder /etc/nginx/sites-enabled contains only my own sites file, and it doesn't mention /robots explicitly. It just has a location block targeting / which gets routed to Gunicorn+Django, and for every site except robots.txt this works just fine. -
Elastic Beanstalk + S3 and easy-thumbnails for django create timeout
I am using the easy-thumbnails module for django. The django app gets deployed on elastic beanstalk and images hosted on S3. When a user uploads an image he gets redirected to a page which shows the thumbnail, generated with easy-thumbnails. This however gives me a 500 Server error. When I wait a little bit and refresh the page, everythings works fine, which leads me to believe that some kind of timeout occurs on thumbnail generation. Of course once the image is generated everything works fine. I could not find any errors in the logs however, even with THUMBNAIL-DEBUG = True. Any leads to a solution would be greatly appreciated. -
While Putting data the through REST API. response is showing {"closingDay":["\"['sunday', 'monday']\" is not a valid choice."]}
I am using Angular JS as frontend. Django as a backend. also using django rest API for CRUD(create,retrieve,update,delete).I am sending data into database through api link. this is my Component.js 'use strict'; angular.module('addshop'). component('addshop',{ templateUrl: 'api/templates/addshop.html', controller : function($scope, $element, $anchorScroll, $location, $mdDialog, $filter, City, Category, SubCategory,Addshop,Map){ $scope.goaddshop = function(shopdata){ Addshop.create({ city : shopdata.city, category : shopdata.category, subCategory : shopdata.subCategory, shopName : shopdata.shopName, tagline : shopdata.tagline, bannerImage : shopdata.bannerImage, email : shopdata.email, mobileNo : shopdata.mobileNo, alternateMobileNo : shopdata.alternateMobileNo, location : shopdata.location, ownerName : shopdata.ownerName, shopAddress : shopdata.shopAddress, shopPinCode : shopdata.shopPinCode, openingTime : shopdata.openingTime, closingTime : shopdata.closingTime, closingDay : shopdata.closingDay, }) } City.query({},function(data){ $scope.cityList = data }); Category.query({},function(data){ $scope.categoryList = data }); SubCategory.query({},function(data){ $scope.subcategoryList = data }); $scope.days = ["sunday","monday" ,"tuesday" ,"thursday" ,"friday", "saturday"]; $scope.states = [ 'Utter Pradesh','Delhi','Jammu & Kashmir','Uttarakhand','Bihar','Rajasthan','Madhya Pradesh','Andaman and Nicobar Islands','Andra Pradesh','Arunachal Pradesh','Assam','Chhattisgarh','Goa','Gujarat','Haryana','Himachal Pradesh','Jharkhand','Karnataka','Kerala','Maharashtra','Manipur','Meghalaya','Mizoram','Nagaland','Orissa','Punjab','Sikkim','Tamil Nadu','Tripura','West Bengal','Pondicherry','Lakshadeep','Daman and Diu','Dadar and Nagar Haveli','Chandigarh'] $scope.scrollTo = function(id,show) { $location.hash(id); $anchorScroll(); }; } }); this is my template <div class="container"> </div> <div class="content" layout="column" layout-align="center center"> <!-- <span style="font-family:inherit; font-size:45px; padding:25px;">List Your Business With CityAPL</span> --> <!-- <a ng-click="scrollTo()" class="cta">Get Start</a> --> </div> </div> <!--add business Form start--> <div layout=column id="foo"> <div style="font-size:31px ; text-align:center;color:#333c ; margin-top:50px; margin-bottom:15px; font-weight:500">List Your Business … -
javascript array object doesn't work with Hicharts when defined through jinja (Django 2.0)
I want to use data passed through a django (2.0) view to my html template - but in JavaScript. I need it to plot an area chart with Highcharts. This is the code context = { 'values': butler.serve(progress) #this works fine } return render_to_response('appfolder/charts.html', context) #this works fine too And this is the charts.html file <script> var values_data = "{{ values }}"; console.log(values_data); //output works </script> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <script src="{% static 'appfolder/js/charts/icam/progress.js%}"</script> and this is my progress.js file Highcharts.chart('container', { chart: { type: 'area' }, title: { text: 'Progress' }, subtitle: { text: 'Source: <a href="http://example.com">' + 'empty for now</a>' }, xAxis: { allowDecimals: false, labels: { formatter: function () { return this.value; // clean, unformatted number for year } } }, yAxis: { title: { text: 'Nuclear weapon states' }, labels: { formatter: function () { return this.value / 1000000 + 'mn'; } } }, tooltip: { pointFormat: '{series.name} churned out USD <b>{point.y:,.0f}</b><br/>million in revenue in {point.x}' }, plotOptions: { area: { pointStart: 2015, marker: { enabled: false, symbol: 'circle', radius: 2, states: { hover: { enabled: true } } } } }, series: [{ name: 'Company', data: values_data }] }); console.log(values_data); //output also works But when … -
How to make Django validators dynamic?
I am new to Django. I am taking over a Django project developed by someone else. They took the basic form validators from here: https://docs.djangoproject.com/en/2.0/topics/auth/passwords/ So if I open settings/common.py I see: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 9, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] My project manager is telling me that she wants these validators to happen while a person is typing, rather than when the form is submit. So I need to somehow make these validators trigger onBlur as the cursor leaves each field. How is this done in Django? -
django - key error in serializer with foreign key models
I checked out all related questions but still curious to know if there exist an updated answer . django serialize foreign key objects So , I have a model which has three foreign keys , next when I am trying to GET a response using that model , they keys in List is appended with "_id" - so whenever I am serializing , I am getting the "KeyError at" error. Error : KeyError at /api/v1/user/skill/upvotes/1 'skill' Model : class UserSkillUpvotes(models.Model): unique_together = (('user_skill', 'upvote_by'),) skill = models.ForeignKey('Skill',on_delete=models.CASCADE , related_name='all_upvote_for_user_skill') upvote_by = models.ForeignKey('auth.User',on_delete=models.CASCADE , related_name='all_upvote_by_user') upvote_for = models.ForeignKey('auth.User',on_delete=models.CASCADE , related_name='all_upvote_for_user') Serializer : class UserSkillUpvotesSerializer(serializers.ModelSerializer): class Meta: model=UserSkillUpvotes fields='__all__' View : if request.method == 'GET': try: user_skill_upvotes = list(UserSkillUpvotes.objects.filter(upvote_for=pk).all().values()) # get all upvotes on skills of the requested user except (UserSkillUpvotes.DoesNotExist,User.DoesNotExist) as e: return HttpResponse(status=404) serializer = UserSkillUpvotesSerializer(user_skill_upvotes,many=True) return Response(serializer.data) Console error - File "C:\code\django\wantedly\src\wantedly_webapp\views\AllViews.py", line 75, in user_skill_upvotes return Response(serializer.data) -
How to transfer logs from centOS to Hadoop Server usign flume without repeating?
I need some help with flume configuration. I have a CentOS server where Django logs are generated over there. I want to read those logs and transfer it to another server. I have 2 configurations available one with one server and another with another server. The issue i am getting is i have used exec command tail -f in config. It is successfully transferring logs from CentOSto Hadoop server.The issue i am facing is the log generating in CentOS is single but when its been transferred to Hadoop Sever its copying twice in it. Can any one help me in this issue. What is the wrong i am doing. Thank you Config in CentOS Server: # configure the agent agent.sources = r1 agent.channels = k1 agent.sinks = c1 # using memory channel to hold upto 1000 events agent.channels.k1.type = memory agent.channels.k1.capacity = 1000 agent.channels.k1.transactionCapacity = 100 # connect source, channel, sink agent.sources.r1.channels = k1 agent.sinks.c1.channel = k1 # cat the file agent.sources.r1.type = exec agent.sources.r1.command = tail -f /home/bluedata/mysite/log/debug.log # connect to another box using AVRO and send the data agent.sinks.c1.type = avro agent.sinks.c1.hostname = x.x.x.x #NOTE: use your server 2s ip address here agent.sinks.c1.port = 9049 #NOTE: This port … -
Django form forms.ModelChoiceField()
I am using forms with the following: class InvoiceModelForm ( forms.ModelForm ): u = forms.ModelChoiceField ( queryset = User.objects.all () ) But in the form field it is displaying the username. I would like to change that to use the first and last names. I do not want to change the def __str__(self): return self.username How can I change what values are displayed in the form field? Thanks. -
User input associates to photo
Working on a blog, where users can create new posts and input a keyword to have a picture associated with that keyword provide a photo for the post. For example: 1) User inputs keyword: 'Pizza' 2) The form page that the user is on either: a) uses that keyword to provide an image associated with it or b) uses that keyword to provide a couple images that the user can then choose from for the image for the post 3) The selected image is then associated with that post Does anyone have suggestions on how to implement this? I'm keen to work on it, but can't even think where to start. Is there a google images plugin that i could use? Or any sample codes? -
forms select2 POST is empty
I'm seeking guidance to get me going in the right direction. My professor is at a loss. I'm having issues with the POST in my form for the select2 multiple fields. I have a Yes/No flag, that determines which select 2 select option to show. The javascript below works great for the show/hide. $(document).ready(function () { $('#option').change(function () { $this = $(this) $('.select_box').each(function () { $select = $('select', this); if ($select.data('id') == $this.val()) { $(this).show(); $select.show().select2(); } else { $(this).hide(); $('select', this).hide(); } }); }); }); My form has a Yes/No/NA option, which dictates what select 2 box to show using the javascript above. <select name ="option" class="form-control " id="option"> <option value="1"> Yes</option> <option value="0"> No</option> <option value="2"> N/A</option> </select> My form POST is handled with the general POST option as shown below: <form action = "{% url 'final' %}" form method = "POST"> Inside my form I have the .select_box div class. The select 2 option gives the correct fields and populates the multi-select correctly. <div id = "div_yesselect" class="select_box"> <script src= "{% static '/accounts/option_select2.js' %}" type="text/javascript"></script> <select data-placeholder="Please select your course(s)?" data-id="1" class="js-example-basic-multiple" multiple="multiple" id = "id_courseselect" value = "{{course.id}}" style="width: 1110px" > {% for course in courses%} … -
Django URL keeps being longer
I am new to django and I am working on url redirects. On my views I am using HttpResponseRedirect and render functions to switch views. The problem is after couple of switching around between views, the URL keeps getting longer. Here is the URL on the chrome after I switched between addcostumer and delete costumer views http://127.0.0.1:8000/interface/addcostumer/deletecostumer/addcostumer/deletecostumer/preview/preview/addcostumer/deletecostumer/ How do I make the URL just http://127.0.0.1:8000/interface/addcostumer/ when I am in addcostumer view and http://127.0.0.1:8000/interface/deletecostumer/ when I am in deletecostumer view insted of them being appended one after another whenever I switch between views. class AddCostumerView(FirstPageView): def __init__(self): super() self.main_template = "addcostumer.html" def get(self, request): form = CostumerForm() return render(request, template_name=self.base_template, context={"company_list": list(database.get_companies()), "sister_page": self.main_template, "form": form}) @method_decorator(csrf_protect) def post(self, request): print("this line is running now") form = CostumerForm(request.POST) if request.FILES["myfile"]: myfile = request.FILES["myfile"] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) if form.is_valid(): data = form.cleaned_data #database.add_costumer(**data) #preview the data and preview the file #Add for final submission #messages.success(request, filename) return HttpResponseRedirect("preview/") # TODO change to proper page return HttpResponseRedirect("firstpage.html") class DeleteCostumerView(FirstPageView): def __int__(self): super() self.main_template = "deletecostumer.html" def get(self, request): companies = database.get_companies() print("delete get request") return render(request, template_name= self.base_template, context={ "company_list": companies, "sister_page" : "deletecostumer.html", "form": DeleteForm(), }) def post(self, … -
DRF - How to Authentify an application with Oauth Toolkit?
In my application, I use a modified User model with 3 more field that I need. from django.contrib.auth.models import AbstractUser from django.db import models import ldapdb.models class User(AbstractUser): cotisant = models.BooleanField(default=False) nbSessions = models.IntegerField(default=0) tel = models.CharField(max_length=20, default="") I want people to be able to change their accounts settings, (like their password, email, tel,...). To do so I have a serializer like this : from rest_framework import serializers from django.contrib.auth.hashers import make_password from coreapp.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'cotisant', 'tel') extra_kwargs = { # Allow to set pwd, but disallow getting the hash from BDD 'password': {'write_only': True} } def validate_password(self, value: str): return make_password(value) And a view like this : class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer permission_classes = (IsSelfOrStaffPermission, TokenHasReadWriteScopeOrCreate,) lookup_field = 'username' def get_queryset(self): current_user = self.request.user if current_user.is_staff: user_set = User.objects.all() else: user_set = User.objects.filter(username=current_user.username) query = self.request.query_params.get('q', None) if not query: return user_set return user_set.filter( Q(username__icontains=query) | Q(first_name__icontains=query) | Q(last_name__icontains=query) ) (This allow access to a user only to himself, unless he is staff) The problem is, to update nbSessions parameter, the user have to pay something on one of my apps. How can I … -
Django 2.0 URL regular expressions
I'm trying set an offset but I want to limit it to a maximum of 99 hours by only allowing either one- or two-digit numbers but I'm not sure of the syntax to use with Django 2.0. I've tried to look for updated documentation but I can't find it, maybe I missed it but I did look before posting here. Here is the code in my views.py file: # Creating a view for showing current datetime + and offset of x amount of hrs def hours_ahead(request, offset): try: offset = int(offset) except ValueError: # Throws an error if the offset contains anything other than an integer raise Http404() dt = datetime.datetime.now() + datetime.timedelta(hours=offset) html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset, dt) return HttpResponse(html) Here is the code from my urls.py file, this allows me to pass an integer but I want to limit this to 1- or 2- digit numbers only: path('date_and_time/plus/<int:offset>/', hours_ahead), I've tried path(r'^date_and_time/plus/\d{1,2}/$', hours_ahead), but I get the Page not found (404) error. Thanks in advance! -
Restricting all the views to authenticated users in Django
I'm new to Django and I'm working on a project which has a login page as its index and a signup page. The rest of the pages all must be restricted to logged in users and if an unauthenticated user attempts to reach them, he/she must be redirected to the login page. I see that @login_required decorator would make a single view restricted to logged in users but is there a better way to make all the views restricted and only a few available to unauthenticated users? -
How to access one to many relationship after bulk_create in Django
I have a problem with accessing bulk inserted one-to-many relationship objects using bulk_create. Here is my code: My models: class Person(models.Model): # ... other fields class Post(models.Model): person = models.ForeignKey(to=Person, related_name="posts") text = models.CharField(max_length=100) # ... other fields Now I want to insert thousands of posts for a person. I'm doing it as follows: person = Person(foo="bar") person.save() posts = [Post(person=person, text="post1"), Post(person=person, text="post2")] person.posts.bulk_create(posts) # Now I want to have an access to the person.posts and pass it to a serializer return PostSerializer(person.posts.all(), many=True).data When I execute, it doesn't populate the relationship => it's empty. I want to perform this without additional query to the database. Is that possible? -
Django: Using Template Tags with ckeditor
I'm using RichTextUploadingField from the ckeditor package for django for my flat pages. I need to insert some urls but I don't want to hardcode them as I'd like to be able to change the urls in the future. If I could do this by using django template language in ckeditor it would be great but I'd be happy just to soft code the urls into the field. -
Django foreign key and one-to-many relationship
I'm trying to build a basic ecommerce website, as a mean to learning django. I'm trying to build my models, so that there is a Category, a Product and Product Image class to store my data in. This is my models.py: class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name', ) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('products:product_list_by_category', args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('name', ) index_together = (('id', 'slug'), ) def __str__(self): return self.name def get_absolute_url(self): return reverse('products:product_detail', args=[self.id, self.slug]) class ProductImage(models.Model): property = models.ForeignKey('Product', related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to='products') And this is my views.py: def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) product_img = Product.images.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'products/list.html', {'category': category, 'categories': categories, 'products': products, 'product_img': product_img}) I've seen similar post here on stack overflow, and have tried to do the same thing, but I still get the following error: AttributeError: 'ReverseManyToOneDescriptor' object …