Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
inAttributeError: module 'reportlab.pdfgen.canvas' has no attribute 'acroform'
I want to create an acroform on PDF in Django by using reportLab. I have already installed the package for reportLab. But when implementing acroform im getting inAttributeError: module 'reportlab.pdfgen.canvas' has no attribute 'acroform' from django.shortcuts import render from django.http import HttpResponse from io import BytesIO from reportlab.pdfgen import canvas from django.http import HttpResponse def index(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"' buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") canvas.acroform.checkbox(name='CB0',tooltip='Field CB0',checked=True,x=72,y=72+4*36,buttonStyle='diamond',borderStyle='bevelled',borderWidth=2,borderColor=red,fillColor=green,textColor=blue,forceBorder=True) # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the BytesIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) return response -
Django ordering by random when using annotate
If I order my queryset randomly and print it out, like this:- [p for p in Player.objects.order_by('?')] it works as you'd expect. The players appear in a random order. And if I order them by the number of games they've played, like this:- [p for p in Player.objects.annotate('games').order_by('games__count')] it also works as you'd expect. The players appear in order of the number of games they've played. But I want to randomise the players that have played the same number of games. So I do this:- [p for p in Player.objects.annotate('games').order_by('games__count', '?')] and it completely breaks it. The query takes a second or two to run, I get the same player over and over, and they're all over the place in terms of order. What have I done wrong? -
Why my Django project in heroku (free) resets database automatically? and loosing my info
I have Deployed my Django project in heroku (free) and add information to model from admin page. But after around 1h it resets PostgreSQL automatically and I'm loosing my information! -
Django cannot load JS files from HTML templates
I am new to Django and Web development. I am stuck at a point. I need to make a graph using Javascript and I successfully done that in file located in app/templates/graphs/BarGraph.js and my HTML template file analysis.html is also in the same folder. It is running fine using Web server Chrome but when I am trying to run my HTML file using my app it does not find my BarGraph.js analysis.html {% extends "header.html" %} {% block content %} <h3 style="text-align:center;">Graph</h3> <script type="text/javascript" src= "templates/graphs/BarGraph.js" ></script> {% endblock %} I also tried to put all the JS code in my HTML, then it does process the code but then does not find frequent_words.tsv file and says BarGraph.js // See D3 margin convention: http://bl.ocks.org/mbostock/3019563 var margin = {top: 20, right: 10, bottom: 100, left:50}, width = 700 - margin.right - margin.left, height = 500 - margin.top - margin.bottom; var svg = d3.select("body") .append("svg") .attr ({ "width": width + margin.right + margin.left, "height": height + margin.top + margin.bottom }) .append("g") .attr("transform","translate(" + margin.left + "," + margin.right + ")"); // define x and y scales var xScale = d3.scale.ordinal() .rangeRoundBands([0,width], 0.2, 0.2); var yScale = d3.scale.linear() .range([height, 0]); // define x … -
Django: Modify User in LDAP
I have a webapp which contains a login and a profile page. I can log-in as a user from the LDAP but I don't know how to modify specific attributes i.e. first_name, last_name or email. I do have some code from another user: class SynchronisingUserAdapter(object): """ This adapts an _LDAPUser object that has been initialised with a correct User object. The layers and layers of wrapping allow this to sit on top of the existing code, but is kind of confusing. The recommended incantation to go from a Django User object to a correctly set up adapter is:: ldap_user = backend.get_user(user.id) sync = SynchronisingUserAdapter(ldap_user) """ group_type = settings.ldap_settings.AUTH_LDAP_GROUP_TYPE group_template = settings.ldap_settings.LDAP_PIXIEDUST_GROUP_DN_TEMPLATE def __init__(self, original): self.original = original self.bound = False def reset_ldap_password(self): """ Set the LDAP Password to an impossible value """ self.connection.modify_s(self.dn, [(self.ldap.MOD_REPLACE, 'userPassword', '{SSHA}!')]) @property def dn(self): dn = self.original.ldap_user.dn if type(dn) == type(u''): return unicode.encode(dn, 'UTF-8') else: return dn @property def connection(self): conn = self.original.ldap_user._get_connection() if not self.bound: self.original.ldap_user._bind() self.bound = True return conn @property def ldap(self): return self.original.ldap_user.ldap def user_attrs(self): """ Create a set of user attributes based on the state of the django user object. """ attrs = generate_attrs(self.original, settings.ldap_settings.AUTH_LDAP_USER_ATTR_MAP) for name, value in settings.ldap_settings.LDAP_PIXIEDUST_DEFAULT_ATTR_MAP.items(): … -
error: [Errno 10053] while submitting ajax form in Django
I saw a similar error already posted here but that did not help to solve my problem. Besides the OP did not provided any information about what he was doing when he encountered that error (as other have said in the comments). What I am trying to do ? I am just trying to register the user to Django with ajax. What is the problem ? I get the following error the movement I submit the form: [15/Jan/2018 17:49:37] "POST /authenticate/register/ HTTP/1.1" 200 14 Traceback (most recent call last): File "C:\Python27\lib\wsgiref\handlers.py", line 86, in run self.finish_response() File "C:\Python27\lib\wsgiref\handlers.py", line 128, in finish_response self.write(data) File "C:\Python27\lib\wsgiref\handlers.py", line 212, in write self.send_headers() File "C:\Python27\lib\wsgiref\handlers.py", line 270, in send_headers self.send_preamble() File "C:\Python27\lib\wsgiref\handlers.py", line 194, in send_preamble 'Date: %s\r\n' % format_date_time(time.time()) File "C:\Python27\lib\socket.py", line 328, in write self.flush() File "C:\Python27\lib\socket.py", line 307, in flush self._sock.sendall(view[write_offset:write_offset+buffer_size]) error: [Errno 10053] An established connection was aborted by the software in your host machine [15/Jan/2018 17:49:37] "POST /authenticate/register/ HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 54896) Traceback (most recent call last): File "C:\Python27\lib\SocketServer.py", line 596, in process_request_thread self.finish_request(request, client_address) File "C:\Python27\lib\SocketServer.py", line 331, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python27\lib\SocketServer.py", line 654, in … -
django template tag with value from from loop [duplicate]
This question is an exact duplicate of: django template tag using for loop value i have django tags as {{ ques.0 }},{{ ques.1 }},{{ ques.2 }} and i wan't to display them using for loop something like this {% for i in ques %} document.getElementById("opt1").innerHTML="{{ ques.i }}"; {% end for %} Its not displaying the data but when i put a value like {{ ques.0 }} it gives the result ,but how can i use it with for loop to display the data Basically i want to pass a value in tags using for loop The main problem to to get value using tags that is generated using for loop in django x=5; for(var i=0;i<x;i++){ document.getElementById("question").innerHTML="{{ ques.i }}"; } -
Problems caused by changing the name of my app when deploying to heroku
The name of my django app was always workout. Then, when I started to deploy it, I thought it'd be a good idea to change the name to workoutcalendar. So I started a new git repo and put my project files in there (not starting a new django project). The only things I changed were the name of the folder workout (the first one of the django project where settings.py is located) to workoutcalendar as well as changing the DJANGO_SETTINGS_MODULE environment variable. Now, I'm running into problems. It seems that parts of my app are looking for a workout module, which they can't find. Example: 2018-01-15T13:06:40.615612+00:00 app[web.1]: Traceback (most recent call last): 2018-01-15T13:06:40.615613+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 135, in handle 2018-01-15T13:06:40.615614+00:00 app[web.1]: self.handle_request(listener, req, client, addr) 2018-01-15T13:06:40.615615+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 176, in handle_request 2018-01-15T13:06:40.615616+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response) 2018-01-15T13:06:40.615617+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 146, in __call__ 2018-01-15T13:06:40.615618+00:00 app[web.1]: response = self.get_response(request) 2018-01-15T13:06:40.615619+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 81, in get_response 2018-01-15T13:06:40.615620+00:00 app[web.1]: response = self._middleware_chain(request) 2018-01-15T13:06:40.615621+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 37, in inner 2018-01-15T13:06:40.615622+00:00 app[web.1]: response = response_for_exception(request, exc) 2018-01-15T13:06:40.615623+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 87, in response_for_exception 2018-01-15T13:06:40.615624+00:00 app[web.1]: response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 2018-01-15T13:06:40.615626+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line … -
How to make sure a form field remains not required after set to required in is_valid?
I have a form, where I have set description as not required. class LeaveApprovalForm(forms.ModelForm): class Meta: model = LeaveRequest description = forms.CharField( widget=forms.Textarea, label='Reason', required=False ) def is_valid(self): '''A description is not required when approving''' self.fields['description'].required = False if self.data.get('reject', None): self.fields['description'].required = True return super().is_valid() However when the form is validated and shows the This field is required. error. The html has the required attribute so if it is not rejected and approved the jquery popup requiring data entry is triggered. How do I ensure when the formis initialises again it is not required? -
Join sql queries for Django
I have two related models: class Category(models.Model): pass class Entry(models.Model): category = models.ForeignKey(Category) is_published = models.BooleanField(default=True) I need to get categories with published entries. I ended up with two queries: published = Entry.objects.filter(is_published=True) categories = Category.objects.filter(entries__in=published) Can I do this in one query? -
installation fixture django-municipios
I am getting the following error when executing the command python manage.py loaddata municipios_geo_2013_4674.json.bz2. how to solve attribute error? Package and json in: https://github.com/znc-sistemas/django-municipios Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 109, in loaddata self.load_label(fixture_label) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/management/commands/loaddata.py", line 175, in load_label obj.save(using=self.using) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/core/serializers/base.py", line 205, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 904, in _save_table forced_update) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/base.py", line 954, in _do_update return filtered._update(values) > 0 File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/query.py", line 664, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1191, in execute_sql cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 863, in execute_sql sql, params = self.as_sql() File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/db/models/sql/compiler.py", line 1157, in as_sql val = field.get_db_prep_save(val, connection=self.connection) File "/Users/lidiane/Developer/django/integra-fundaj/.myvenv/lib/python3.5/site-packages/django/contrib/gis/db/models/fields.py", line 182, in get_db_prep_save return connection.ops.Adapter(self.get_prep_value(value)) AttributeError: Problem installing fixture '/Users/lidiane/Developer/django/integra-fundaj/municipios_geo_2013_4674.json': 'DatabaseOperations' object has no attribute 'Adapter' -
Recursion error calling a function using a post-save signal
I have a Category model, where the ForeignKey is to self. class Category(SEO, MetaData): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) path = ArrayField(models.IntegerField(), blank=True, null=True) I introduced the path field, to avoid recursion in widget, and do it model, because is not often done. I use a post_save signal to ssave the path: def _recurse_for_parent(cat_obj, path=None): # path at the beginning don't exist and need to be initialized if not path: path = [] if cat_obj.parent is not None: _recurse_for_parent(cat_obj.parent, path) return path def save_path(sender, instance, **kwargs): if instance.parent_id: instance.children = _recurse_for_parent(instance.parent) instance.save() post_save.connect(save_path, sender=Category) My issue is that I get the "maximum recursion depth error" and I don't see why, because I use the condition: cat_obj.parent is not None: -
Heroku app crashes upon first deployment attempt
I've been trying to deploy my workoutcalendar app on heroku. After a lot of progress I finally successfully pushed to heroku master and ran makemigrations and migrate. Unfortunately, when it was time to go to the page and see my beautiful website, I was instead greeted by this: As instructed by the message in my browser, I checked the logs in the hope of finding further information of the error. But all I found was this: 2018-01-15T12:22:54.915142+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=workoutcalendar.herokuapp.com request_id=46d30e9c-d76c-451b-bbb6-ccbfef5efa72 fwd="130.229.155.250" dyno= connect= service= status=503 bytes= protocol=https This doesn't tell me much. The only thing I wonder is why path=/favicon.ico. That's not a url that I've defined on my site. I don't know if that's the reason for the crash. In any case, I wonder if you could tell me how to solve this error, or how to find more information on how to solve it. PS: Some additional info... My requirements.txt: dj-database-url==0.4.2 Django==2.0.1 django-secure==1.0.1 djangorestframework==3.7.1 gunicorn==19.7.1 psycopg2==2.7.3.2 python2==1.2 pytz==2017.2 six==1.10.0 whitenoise==3.3.1 My Procfile: web: gunicorn workoutcalendar.wsgi --log-file - My runtime.txt: python-3.6.4 -
Django Taggit: add defaut tag to object
What's the best practice to add a default tag to an object? This is what I wish to do: class Exercise(Model): tags = TaggableManager(blank=True) class TrueOrFalseExercise(Exercise): def __init__(self, *args, **kwargs): super(Exercise, self ).__init__(*args, **kwargs) self.tags.add("true or false") //but this will not work because self doesn't exist yet It will give me error: objects need to have a primary key value before you can access their tags. Is there an elegant way to acheive this? If possible I prefer not to add it through my already messy tag widgets. -
Django json array in models
I have a model in my app which I used Django rest framework. I want to have an array of json objects like below: class AddOn(models.Model): name = models.CharField(max_length=128) plans = ArrayField(JSONField(default=dict)) now after migration and register this model in admin.py file when i go to Django admin to create a record in DB, following error throwing: column "plans" is of type jsonb[] but expression is of type text[] LINE 1: ..."paas_addon" ("name", "plans") VALUES ('mongodb', ARRAY['{"a... ^ HINT: You will need to rewrite or cast the expression. I guess model want to have a JSON object but it gets an array of string instead. how can fix this? should i overwrite save method -
Business logic validations in Django: Model or ModelForm?
Suppose I have the following model: class Location(models.Model): name = models.CharField(max_length=32) class Event(models.Model): start = models.DateTimeField() end = models.DateTimeField() location = models.ManyToManyField(Location) The Event model has two invariants: end can't be before start a Location can't have overlapping events What would be a better pattern in Django: validating this in your form (EventForm.clean_end()) or in your model (Event.clean())? According to the docs, when you define a clean() method in your model, it won't be automatically called when using save(), so when manipulating objects outside the Form API I can't really see the added value (unless you call full_clean() by yourself). Also, in my case, my application only has one EventModelForm which manipulates Event objects, so both options would be equally DRY. In short: should I put these kind of validations in my models or in my forms? -
How to specify Parent-Child relationship withing one Model?
For example I have following code: class FamilyMember(models.Model): user = models.OneToOneField(User) And I have following situations: a1 = FamilyMember.objects.get(id=1) a1.first_name = 'John' a1.last_name = 'Smith' (a1 is a parent of a2) a2 = FamilyMember.objects.get(id=2) a2.first_name = 'Mark' a2.last_name = 'Smith' (a2 is a child of a1 and parent of a3 in the same time) a3 = FamilyMember.objects.get(id=3) a3.first_name = 'Jason' a3.last_name = 'Smith' (a3 is a child of a2) How can i accomplish that kind of relationships within one model ? -
Send filepath as getURL parameter Django2
I want to send a file url as a get parameter: $.get("/django_route/"+ encodeURIComponent(fileUrl), function(res){ console.log(res) }) But it looks like Django is interpreting my encoded URI component as an actual URI... Is this kind of thing possible with Django? -
How to change manager for custom User model
I've defined a custom user model: class User(AbstractUser): REQUIRED_FIELDS = [] USERNAME_FIELD = 'email' email = models.EmailField( _('email address'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Must be a valid email address.'), error_messages={ 'unique':_("A user with that email address already exists."), }, ) The point of it being to use an email address instead of username. I've put this in settings: # custom user model AUTH_USER_MODEL = 'workoutcal.User' The user model works, but there's one problem. I can't create superusers: (workout) n155-p250:workout sahandzarrinkoub$ ./manage.py createsuperuser Email address: sahandz@kth.se Password: Password (again): Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 179, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' Seems like the create_superuser method used has username as a required argument. I've read in the docs that I need to implement my own CustomUserManager. I've already done so here: class CustomUserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): now = … -
Django model attribute that updates when database is updated
I am a django beginner trying to set up a django project for data analysis. Data from a certain type of experiment is represented by two models "Dataset" and "GeneEntry", where each Dataset represents one experiment and every GeneEntry is one line from a dataset. Each dataset contains around 20000 entries. A gene with the same name can occur with the same gene symbol in multiple datasets. class Dataset(models.Model): dataset_name = models.CharField(max_length=200) def __str__(self): return self.dataset_name class GeneEntry(models.Model): dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE) gene_symbol = models.CharField(max_length=200) Pval = models.FloatField(default=0) x = models.IntegerField(default=0) y = models.IntegerField(default=0) def __str__(self): return self.gene_symbol On my django project, users can select one of the datasets and plot x vs. y. The colors of the datapoints should be allocated according to a colorscale on a gene specific ratio r = a/b. b is the number of times this exact gene_symbol appears in the database (e.g. 8 out of 10 experiments have this gene -> a = 8) and a is the number how many of these entries have a Pval < 0.05. Currently, I am doing this by looping over a list with gene names and calling the following method for all of them: def outlier(self, gene): … -
Create a edit view in django to modify the existing issues
I have been trying to work out how to create a edit view in django but everything I try keeps on failing and not giving me the ability to edit the already saved objects.The issues get created fine and saved and displayed but I just cant load them for editing.The code is bellow any help or advice would be good. views.py class IssueListView(ListView): template_name = 'issuetracker/issue_list.html' def get_queryset(self): slug = self.kwargs.get("slug") if slug == 'open': queryset = Issue.objects.filter(status__iexact="assigned") else: queryset = Issue.objects.all() return queryset class StatView(View): def get(self,request): if Issue.objects.filter(status__iexact="c").exists(): closed_lst = [] seconds = [] idx = 0 count = 0 queryset = Issue.objects.filter(status__iexact="closed") queryset1 = Issue.objects.filter(status__iexact="c") for tkt in queryset1: count = count + 1 times1 = queryset1.order_by().values_list('updated').distinct() times = queryset1.order_by().values_list('opened').distinct() final = times1[idx][0] - times[idx][0] sec = final / timedelta(seconds=1) idx = idx + 1 seconds.append(sec) mx = max(seconds) mn = min(seconds) av = sum(seconds) / len(seconds) maximum = (str(mx * timedelta(seconds=1)).split('.')[0]) minimum = (str(mn * timedelta(seconds=1)).split('.')[0]) average = (str(av * timedelta(seconds=1)).split('.')[0]) all_docs = len(Issue.objects.all()) - count return render(request,"issuetracker/main.html",{ 'maximum':maximum, 'minimum':minimum, 'average':average, 'count':count, 'all_docs':all_docs }) else: return render(request, "issuetracker/main.html") class FormView(FormView): template_name = 'issuetracker/form.html' form_class = CreateIssueForm success_url = '/issue/' def form_valid(self, form): obj = Issue.objects.create( submitter=form.cleaned_data.get('submitter'), … -
How to set up a web server in LAN?
I looked for this answer a lot but I didn't find an answer that can help me. I developed a django application that allows admin to upload files by the default admin page. I want to allow users to download these files by clicking on a download link.I know that files can't be served with django itself because it's not a web server. The server has centOS. Which web server should i use and how to set up it? I just want to use my application in my house LAN. -
Financial budgeting and cash-flow management app like pulseapp or floatapp
I am new to the Stack Overflow site and for that manner new to coding in general. I am a financial consultant by trade but am starting to see real opportunities in learning how to code and develop simple webapps for my clients. My idea is to develop an web based application for budgeting and cash-flow management for small and medium size enterprises for our local market which has its own accounting standards and therefore the already made solutions do not come into play. Basically I would like to develop an app similar to pulseapp or floatapp. I already have the financial model done in excel but would really benefit from a fully developed webapp. I have already started to learn python as I researched that it was most appropriate coding language for such solutions. I also learned a bit of django. My question is am I on the right track regarding the development environment (django/python) and do you maybe know how the above mentioned app are designed (which language or technology is used). Additionally I would kindly ask you for any suggestions on how I would go about learning how to develop such a webapp (tutorials, resources, tips, ideas). … -
Any remaining kwargs must correspond to properties or virtual fields - what does it mean?
I was trying with different model relationships, when came across this exception (please write if you want to see the full traceback): File "C:\Users\1\vat\tpgen\tpgen\src\generator\views\wizard.py", line 172, in get_next_form return step, form_type(**kwargs) File "C:\Users\1\vat\tpgen\venv\lib\site-packages\django\db\models\base.py", line 495, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) TypeError: 'data' is an invalid keyword argument for this function As I understand, the exception was raised when Django tried to create a new instance with some kwargs. The traceback points to Models’ __init__ method in django.db.models.base if kwargs: property_names = opts._property_names for prop in tuple(kwargs): try: # Any remaining kwargs must correspond to properties or # virtual fields. if prop in property_names or opts.get_field(prop): if kwargs[prop] is not _DEFERRED: _setattr(self, prop, kwargs[prop]) del kwargs[prop] except (AttributeError, FieldDoesNotExist): pass for kwarg in kwargs: raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) The kwargs seems to be all right (printed from the line 171 of wizard.py): {'data': None, 'prefix': '2', 'initial': {'0': {'0-trans_type': ['13'], '0-end_of_tax_year': ['']}, '1': {'1-funct_title': ['14']}}} So the problem, as I understand it, lies in the model, which I admit is a bit overcomplicated, but as said before, I was experimenting with models relationships. The … -
Django ValueError sending forms to template
I have just added another form to send to my template and I have begun to have this error. It isn't very descriptive so I can't work out what I've done wrong. The error is ValueError: too many values to unpack (expected 2). views.py: def new_post(request): if request.method == 'POST': form = NewPostForm(request.POST) election_form = ElectionSuggestionForm(request.POST, request.user) if form.is_valid(): post = form.save(commit=False) post.author = Candidate.objects.get(UserID=request.user, ElectionID=election_form.PostElection) post.save() return redirect('/feed/') else: form = NewPostForm() election_form = ElectionSuggestionForm(request.user) return render(request, 'campaign/new_post.html', { "form": form, "election_form": election_form, }) I think the error comes from the last line - the "election_form" item in the dictionary - which is confusing since there are only 2 items passed in the dictionary, thus contradicting the error message. Here is the offending form (The view was working with only NewPostForm() so I haven't included this.): forms.py: def GetAvailableElections(user): candidates = Candidate.objects.all().filter(UserID=user) choices = [] for i in candidates: choices.append(i.ElectionID.Name) return choices class ElectionSuggestionForm(forms.Form): def __init__(self, user, *args, **kwargs): super(ElectionSuggestionForm, self).__init__(*args, **kwargs) self.fields['PostElection'] = forms.ChoiceField(choices=GetAvailableElections(user)) Thanks in advance.