Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use one database for Django, Android and other
I develop a web system by Django. now, I want connect a Android app and ios app to it. they must Django database for login, post, comment, ... and don't know what to do. is rest api usefull and safe? please answer -
Storing wall-clock datetimes in Django/Postgres
I want to save a future wall-clock datetime for events in Django (I have timezone string stored separately). I can't simply use the DateTimeField because it enforces timestamp with time zone and always saves time in current timezone. It doesn't handle DST or possible timezone changes between current date and the date of actual event. I could use any of these options: Pick any timezone to store timestamps and always throw this timezone away before applying actual timezone in Python. Split timestamp to DateField and TimeField. Store datetime as string. Custom field that stores datetime as timestamp without time zone. but it makes queries more difficult and seems quite weird. Are there any better options I miss? This usecase seems quite common so I guess there is a better way to do that? -
How to use variable at start of django url to return to view?
I am trying to pass the first part of a django url to a view, so I can filter my results by the term in the url. Looking at the documentation, it seems quite straightforward. However, I have the following urls.py url('<colcat>/collection/(?P<name>[\w\-]+)$', views.collection_detail, name='collection_detail'), url('<colcat>/', views.collection_view, name='collection_view'), In this case, I want to be able to go to /living and have living be passed to my view so that I can use it to filter by. When trying this however, no matter what url I put it isn't being matched, and I get an error saying the address I put in could not be matched to any urls. What am I missing? -
How to reset the password in Django
I am using the password reset function in django for resetting the password. settings.py: ------------- EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'xxxxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxxxxx@99' EMAIL_PORT = 587 urls.py: --------- url(r'^password_reset/$', auth_views.PasswordResetView, name='password_reset.html'), views.py: --------- def password_reset(request): print ("entered the fn") subject = "please change the password" message = "please reset it" to_list = ['xxxxxxxx@gmail.com'] send_mail(subject, message, to_list, fail_silently=True) but when i am entering the email to reset it i am getting the following error: smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbsX\n5.7.14 CBaTzAk4DIKFcdsgkGIv0Lgp1EdvehV4fsLoBw-Ix7_G5jQXYN8Ug0HFH-jO6UIjiar2nC\n5.7.14 Nd2dL4HXSYN4Oiazo88whyg8bSkbikpebbnb8E9JzDNTPT8s2b4vAgWrD87xNVpe1DGE94\n5.7.14 VGnf_nPjyyVW1R7xJaYpl8s23hB8fPcEYiPugPUPKjusMagyaOjZNG7v> Please log\n5.7.14 in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 d6sm10486629pfg.47 - gsmtp') -
How to use fieldsets without causing registry() error?
New to django. I was trying to modify my model to get 2 fields on the same line. After reading documentation on https://docs.djangoproject.com/en/2.1/ref/contrib/admin/ I tried the following in admin.py: from django.contrib import admin from .models import * # Register your models here. class NewsAdd(admin.ModelAdmin): fieldsets = [ (None, { 'fields': ('field1'('field2','field3'),'field4','field5','field6','field7')})] admin.site.register(News, NewsDisplay, NewsAdd) Please don't mind the News and NewsDisplay in admin.site.register as those work correctly. As soon as I add NewsAdd to admin.site.register() I get the following error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000000044C5E18> Traceback (most recent call last): File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python36\lib\site-packages\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Python36\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Python36\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Python36\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line … -
How to make a pop up generated file download in Django 2?
I was working on a barcode image generate system and make pdf for printing. Here is my view.py from reportlab.pdfgen import canvas from reportlab.lib.units import inch, cm from reportlab.platypus import Paragraph canvas.Canvas('assets/pdf_print/'+barCode+'.pdf') c.drawImage('1.png',0.9*cm,0,3.5*cm,1.8*cm) c.drawImage('1.png',4.8*cm,0,3.5*cm,1.8*cm) c.drawImage('1.png',8.9*cm,0,3.5*cm,1.8*cm) c.drawImage('1.png',12.7*cm,0,3.5*cm,1.8*cm) c.drawImage('1.png',16.7*cm,0,3.5*cm,1.8*cm) c.showPage() c.save() I save that pdf file in this path successfully using report lab assets/pdf_print/ After saving that file in that path, I need to generate a popup download for this file. How could I do that in Django? -
Django ORM filter gives a QuerySet Object which i am unable to retreive data from
-----------------------------Models----------------------------- class Pattern(models.Model): name = models.CharField(_("Pattern Name"), unique=True, max_length=32) created_on = models.DateTimeField(_("Created On"), editable=False, auto_now_add=True) class Base(models.Model): l_shoulder = models.ImageField(_("Left Shoulder"), upload_to='left_shoulders/') r_shoulder = models.ImageField(_("Right Shoulder"), upload_to='right_shoulders/') l_front = models.ImageField(_("Left Front"), upload_to='left_fronts/') r_front = models.ImageField(_("Right Front"), upload_to='right_fronts/') l_collar_base = models.ImageField(_("Left Collar Base"), upload_to='left_collor_bases/') r_collar_base = models.ImageField(_("Right Collar Base"), upload_to='right_color_bases/') yoke_bottom = models.ImageField(_("Bottom Yoke"), upload_to='neck_bottoms/') yoke_top = models.ImageField(_("Top Yoke"), upload_to='neck_tops/') placket = models.ImageField(_("Placket"), upload_to='plackets/') pattern = models.OneToOneField(Pattern, on_delete=models.CASCADE) class Collar(models.Model): CATAGORY_CHOICES = ( ('RR', 'Regular'), ('BR', 'Big Round'), ('CA', 'Cut Away'), ('DB', 'Dual Button'), ('PH', 'Pin Hole'), ('SW', 'Semi Wide'), ('RB', 'Round Button Down'), ('SP', 'Short Point'), ('SS', 'Stand'), ('WS', 'Wide Spread'), ) inner = models.ImageField(_("Inner Collar"), upload_to="inner_collars/") upper = models.ImageField(_("Upper Collar"), upload_to="upper_collars/") outer_r = models.ImageField(_("Outer Right Collar"), upload_to="outer_right_collars/") outer_l = models.ImageField(_("Outer Left Collar"), upload_to="outer_left_collars/") catagory = models.CharField(max_length=2, choices=CATAGORY_CHOICES) pattern = models.ForeignKey(Pattern, related_name="collar", on_delete=models.CASCADE) -----------------------------Views----------------------------- def design(request): pattern = Pattern.objects.get(name="p1") collar = pattern.collar.all().filter(catagory="RR") cont = { "base": pattern.base, "collar": collar, } return render(request, 'shirts/shirtdesign.html', context=cont) In template, I am unable to retreive image urls by {{ collar.inner.url }} or {{ collar.upper.url }} etc. I am not sure what's wrong. When i try to print collar in views as print(collar) it gives <QuerySet [<Collar: Collar object (1)>]>. I am not sure what … -
Django2.1: Geometry Field on admin site change view with has_view_permission()
I'm looking for the correct way to display a map field with the default OSM widget on an admin change form for a user with has_view_permission() only. I understand this kind of permission will give users read-only access to models in the admin. And all the fields displayed are going to be read-only fields, as the default has_change_permission() is setted to False. And as Django default behaviour require for geometry fields in read_only_fields, data will be displayed as WKT field. I tried to override the form as the django release note advised: # models.py from django.contrib.gis.db import models class Adress(models.ModelAdmin): text_block = models.TextField( "Full Adress", blank=True, null=True) geom = models.PointField( "Position WGS84", blank=True, null=True, geography=True) # admin.py from my_app.models import Adress class AdressAdmin(geo_admin.OSMGeoAdmin): modifiable = True fieldsets = ( ('My adress', { 'fields': ( 'text_block', )}), ('Position', { 'fields': ( 'geom', )}), ) def get_form(self, request, obj=None, **kwargs): if not self.has_change_permission(request, obj): return AdressViewAdminForm return super().get_form(request, obj, **kwargs) admin.site.register(Adress, AdressAdmin) # forms.py class AdressViewAdminForm(forms.ModelForm): class Meta: model = models.Adress fields = ('text_block', 'geom',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) instance = kwargs.get('instance', None) if instance and instance.geom: self.fields.get('geom').widget.attrs['read_only'] = False And force read_only attribute to the geom field to False. … -
How to make my reply form receive input from django?
Hey guys I was making a reply form from which users can reply to the comments,I use the comments form two times 1st for the comments itself , 2nd for the reply .BUT when i initialize the form for replies .It gives me the data of the model .It doesn't appear as a form Here's the models.py of comments and replies class CommentManager(models.Manager): def all(self): qs = super(CommentManager,self).filter(parent = None) return qs class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments") name = models.CharField(max_length = 200) body = models.TextField(default = True) pub_date = models.DateTimeField(auto_now_add = True) parent = models.ForeignKey('self',null = True,blank = True) class Meta: ordering = ['-pub_date'] def __str__(self): return self.name def replies(self): return Reply.objects.filter(parent = self) @property def is_parent(self): if self.parent is not None: return False return True Here,s the views.py of comments and replies def BlogDetail(request,pk): post = get_object_or_404(Post,pk = pk) comment = CommentForm( request.POST or None) subscribe = Subscribe() parent_obj = None if request.method == 'POST': subscribe = Subscribe(request.POST) comment = CommentForm(request.POST) if comment.is_valid(): comment.instance.post = post comment.save() return redirect('index') try: parent_id = request.POST.get('parent_id') except: parent_id = None if parent_id: parent_qs = Comments.objects.filter(id = parent_id) if parent_qs.exits(): parent_obj = parent_qs.first() elif subscribe.is_valid(): subscribe = subscribe.save(commit = True) return … -
Django-admin , show image
I have several images attached to an obj, and i want to show all the images in a small box. Models 1 class Model1(models.Model): ........ Model 2 class Imagem(models.Model): model1 = models.ForeignKey(Avaria) imagem = models.ImageField(upload_to=get_image, blank=True, null=True) Models 1.ADMIN class ImagemInline(admin.StackedInline): model = Imagem extra = 0 max_num = 3 class Moddel1Admin(admin.ModelAdmin): inlines = [ImagemInline] -
Access to content of CharField before clean
I have custom django field based on django CharField (django versoon=1.6): class MyHTMLField(forms.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = kwargs.get('max_length', settings.MAX_MYHTML_SIZE) super(MyHTMLField, self).__init__(*args, **kwargs) And this is how I use it in API function to validate the input: validation_field = MyHTMLField() try: validation_field.clean(html_content) except forms.ValidationError: errors = validation_field.errors The problem is following: max_length depends of content the html_content string, because there are few types of content and we have different length restrictions for them. So we have function (simplified) to get the content type: def get_content_type(html_content): return 1 if "sign" in html_content else 0 Before this time we used this function only after validation of MyHTMLField. And now I have to detect type of content before running MyHTMLField.clean() method to pass the correct max_size to it dynamically, not just from settings constant. But is it wight way to parse the not-validated content before running .clean() method? I know that MyHTMLField.clean() will run django function `run_validators" and only validator for now is length check. But may be there are some hidden extra checks on the safety of input text? -
Django - mail_admins() and mail_admins logging not working
I need to configure my project so that it sends email to administrators on Internal Server Error. I followed related documentation, but can't get it working. I've also tried to use mail_admins() method and it's also not working (not sending a thing), though digging in its code it should. I should specify that I can properly send emails with send_mail() and I can't see anything related in logs. Here are relevants settings : DEBUG = False SERVER_EMAIL = DEFAULT_FROM_EMAIL ADMINS = [('Admin1', 'admin1@domain.com'), ('Admin2', 'admin2@domain.com')] LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(asctime)s %(message)s' }, 'django.server': DEFAULT_LOGGING['formatters']['django.server'], }, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': LOGFILE, 'formatter':'simple' }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', #'include_html':True, }, 'django.server': DEFAULT_LOGGING['handlers']['django.server'] }, 'loggers': { 'django': { 'handlers': ['file', 'mail_admins'], 'propagate': True, }, 'django.server': DEFAULT_LOGGING['loggers']['django.server'] }, } -
Saving same data from parent model into childs - Django 1.11
I'm a bit confused about this, I don't seem to find the exact answer to this problem, not sure about which approach will be safer to do this. I have a parent model, and 2 child models, I'm using django forms, what I want, is to fill the 2 child models whenever the parent is field, I mean, they look like this: class Parent(models.Model): field1 = models.CharField() field2 = models.CharField() field3 = models.CharField() class Child1(Parent): pass class Child2(Parent): pass Since I don't want/need to create new fields on the child classes, everything is going to be inherited from the parent one, I can use the parent's fields on admin or forms without problems. But what I actually want, is whenever the Parent fields are filled and saved into db, the same fields (or data) should be saved on Child1 and Child2 as well. Any ideas on how to achieve this? -
django rest framework get all fields and related fields
I'm new in Django I want to get all informations of my contacts for a store given in parameter and all extra from another model. Here is my code : Models.py class Store(models.Model): name = models.CharField(max_length=100) class Contact(models.Model): id = models.CharField(primary_key=True, max_length=200) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) email = models.CharField(max_length=100, null=True, blank=True) stores = models.ManyToManyField(Store, related_name='contacts') class DataType(models.Model): datatype = models.CharField(max_length=10) class DataField(models.Model): name = models.CharField(max_length=100) label = models.CharField(max_length=100) datatype = models.ForeignKey( 'DataType', on_delete=models.SET_NULL, null=True ) class DataFieldValue(models.Model): contact = models.ForeignKey( Contact, on_delete=models.SET_NULL, related_name='datafieldvalues', null=True ) datafield = models.ForeignKey( 'DataField', on_delete=models.SET_NULL, null=True ) value = models.CharField( max_length=250, null=True, blank=True ) Views.py # Contact API views. class ContactListAPIView(generics.ListAPIView): queryset = Contact.objects.all() serializer_class = ContactSerializer filter_class = ContactFilter Filters.py class ContactFilter(django_filters.rest_framework.FilterSet): store = django_filters.CharFilter() class Meta: model = Contact fields = ['store'] Serializers.py class ContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = '__all__' (Additionnal) Here is the schema : schema this is what i want: GET /contacts/?store=54 { "count": 25, "next": "<url>/contacts/?page=3", "previous": "<url>/contacts/?page=2", "data": [ { "id": "a519d2cd-13c6-48f3-b391-9a7e0cee58cc", "src_id": 356, "first_name": "Benjamin", "last_name": "Pavard", "email": "benjamin.pavard@email.fr", "datafields" : { "age" : "eighteen" }, "store": 54 }, .... ] } but this is … -
'str' object has no attribute 'visible_fields'
I keep getting this error: 'str' object has no attribute 'visible_fields' {% load bootstrap %} {{ wizard.management_form }} <div class="form-horizontal"> {{ wizard.form|bootstrap_horizontal:'col-sm-3 col-md-3' }} </div> but i really have no idea where does it come from, can anyone help me? This is what my login view looks like: def login_request(request): if request.method == "POST": if result['success']: form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("main:homepage") else: messages.error(request, "Invalid username or password") else: messages.error(request, "Invalid username or password") form = AuthenticationForm() return render(request, "log.html", {"form":form}) -
Create dynamic file path by passing unique id to another model Django
I am using MySQL database. I want to store project images in a different table since one project could have any number of files. models.py classes class Project_Details(models.Model): project_user_uid = models.CharField(max_length=10) project_uid = models.CharField(max_length=8, unique=True) project_name = models.CharField(max_length=50) project_address = models.CharField(max_length=200) def project_directory_path(instance, fileDomain): return 'project/{0}/{1}'.format(instance.files_project_details_uid, fileDomain) class Project_Files(models.Model): files_project_details_uid = models.CharField(max_length=500) files_ImageType = models.FileField(upload_to=project_directory_path, max_length=500) The desired path is <MEDIA ROOT>/project/Project_Details.project_uid/fileDomain For eg: project/18030012/BuidingImage But the path I get is project/Project_Files object(none)/BuidingImage Can I pass Project_Details.project_uid to project_path_directory method by passing parameters project_path_directory method to or is there another way around? I am newbie with Django. Any help will be appreciated? -
How can I add a title to the exported data in django tables2
I am using Django tables2 to render data in a table and export data. However, I also want to add a title to the excel sheet created. I have been able to add additional data as follows, and I would like to add the title exporter = TableExport( export_format=export_format, table=self.table, exclude_columns=self.exclude_columns ) exporter.dataset._data.append('') exporter.dataset._data.append(['Report generated by %s.' % (self.request.user.get_full_name())]) exporter.dataset._data.append(['Generated on: %s' % (datetime.datetime.now().ctime())]) I have checked the attributes of the exporter object (dir(exporter)) and found the title attribute. I tried exporter.dataset.title = 'My Report Title' but it doesn't seem to work -
Django CreatView def get_initial method not updating the select option form field
I am trying to set the 'campaign' foreignkey field which is a select option field in html form to a initial value of an integer passed from the url. The campaign_id value perfectly reaches the get_initial method of the view that i have written but still the html form doesn't pick that value and doesn't set the select option field even though the campaign_id i am passing from the urls.py exists in the Campaign Table. #models.py class CampaignDetails(Timestamp): compaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) caption_example = models.TextField(max_length=500) #url.py path('create/details/<int:campaign_id>/', CampaignCreateDetails.as_view(), name='create-details'), #views.py class CampaignCreateDetails(CreateView): model = CampaignDetails fields = '__all__' template_name = 'campaign/campaign_details_create.html' success_url = '/brand-list/' def get_initial(self): return { 'campaign': self.kwargs.get('campaign_id') } # campaign/campaign_details_create.html <form method="post" enctype="multipart/form-data">{% csrf_token %} {{form.errors}} {{form.as_p}} <button class="btn waves-effect waves-light" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </form> -
Custom DjangoAdmin authentication
I try to custom the Django Admin authentication like the Gmail one. Where first the User will enter his email address and then he will have to enter his password or will be redirect to another Identity Provider. If not logged in, Django default will redirect to /admin/login/?next=/admin/. I would like to redirect to an url where the user has to enter his login, I will evaluate the domain name, and then he will have to enter his password. Could you please advice on which approach to achieve this ? What I have so far: A model for the domain name Create the page where the email address is evaluated def redirect_user(request): if request.method == "POST": email = re.findall('.*@(.*)\.', request._post["email"]) if len(email) == 1: domain = email[0] # redirect to SAML if Domain.objects.filter(sso_domain=domain).exists(): return redirect('/authentication/redirect/') # redirect to Django Admin else: return redirect('/admin') return render(request,'authentication/email_login.html', {}) -
How can I enter information into a form without the text box appearing?
I am new to Django and Python, (about two weeks in). I am using a class-based view to create a form. This is working fine to output the form, but the problem I have faced with is the category shows up as a text box (as it should), but I would like to use something like class ClassifiedCreateView(CreateView): model = Listing fields = ['title', 'description', 'price', 'picture', 'shipping','category'] template_name = 'listing/create.html' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) I would like to use something like a drop-down menu to get the information into the database like. <select name="category"> <option value="categoryA">CategoryA</option> <option value="categoryB">CategoryB</option> </select> My models.py file. class Listing(models.Model): picture = models.ImageField(default='default.jpg',upload_to='classified_pics') list_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=20) title = models.CharField(max_length=80) description = models.TextField(default='Please include a description.') price = models.DecimalField(max_digits=6, decimal_places=2, default=0.00) shipping = models.BooleanField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Classifieds Listing' def get_absolute_url(self): return reverse('classified-details', kwargs={'pk': self.pk}) I'm open to change anything as long as I can get the category field as pre-set. By the time it is done, I will have about 10 categories each containing 10+ sub-categories. The 'sub-category' will be the thing that needs to populate the category field. -
Problems sending input file from Vue.js to Django with Django Rest Framework
I am trying to send a form from Vue.js to Django with DRF. But the response is 400 Patch error: {"file":["The submitted data was not a file. Check the encoding type on the form."]} It is my template in Vue.js: Template: <input type="file" id="file" ref="file" class="input is-rounded" v-on:change="handleFileUpload()"/> And here is Vue methods. I send enctype: 'multipart/form-data' and I think that I am using the correct way to send the file. Anyway, I think that here is the problem, maybe this.file is not sending the file correctly. HTTP is a constant to Axios: "const HTTP = axios.create({})" methods: { handleFileUpload(){ this.file = this.$refs.file.files[0]; }, create: function () { this.token = this.$store.state.access_token; HTTP({ method: 'PATCH', url: 'tickets/create/', enctype: 'multipart/form-data', headers: { 'Authorization': `Bearer ${this.token}`, }, data: { file:this.file, } }) .then(response => { ... And here my view.py method: @csrf_exempt @api_view(['GET', 'POST','PATCH']) def Create(request): parser_classes = (FileUploadParser,) if request.method == 'PATCH' or request.method == 'POST': serializer = CreateTicketSerializer( Tickets, data=request.data ) serializer.is_valid(raise_exception=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #Return this if request method is not POST return Response({'ok': 'false'}, status=status.HTTP_200_OK) And my Serializer: class CreateTicketSerializer(serializers.ModelSerializer): """Ticket serializer.""" file = serializers.ImageField(required=False,max_length=None, use_url=True) class Meta: model = Tickets fields … -
Can Python Functions be used in Flask or Django?
I need help with a question I have in mind.I've been working on big data and machine learning lately.I'm going to do some work on twitter data first, but I don't want my work to remain only on the terminal screen.I want to see the data on the web, is it possible using flask or django?It doesn't have to be just twitter data, as I said at first, it could be any data. -
No such table: main,base_category__old
Recently I updated my Node, which broke my environment. I fixed it but had to update brew. I think this also updated/somehow changed my sqlite installation which broke my Django (2.0.6) app. Since I'm on MacOS a version came pre installed. This was sqlite 3.25. I tried to update this version in a clean way, but ended up just replacing the executable in local/usr/bin. Now when I call sqlite3 from the terminal it says: SQLite version 3.27.1 2019-02-08 13:17:39 I updated SQLite because I found this question. Since this is a bug in SQLite 3.26 I wasn't quite sure whether this was the exact problem I had. I updated to 3.27.1 and this didn't solve my issue. I also installed SQLite through brew, that installation is also on 3.27.1 Since the bug report on above mentioned question says the bug is fixed and I updated both versions to the most recent one I'm not really sure what else I can try.. Some other things I tried: - Delete the database and rerun migrations - Delete all present migrations, create a single one and migrated it - Reinstalling the SQLite brew installation - brew link sqlite: Warning: Refusing to link macOS-provided … -
getting Error KeyError: (8, 'occurred at index 0') while integrating python code with Django . The code works in spyder
I am trying to integrate a python code which works independently in spyder with Django which i am running in Atom. Code below import pandas as pd import datetime month = request.POST.get('month') start_month_no = request.POST.get('start_month') month = int(month) fin_data = pd.read_excel('C:\Resh\PythonWorkingDir\sample.xlsx', header=0) fin_data = fin_data.drop(['Clarity Code', 'Additions to Projection if any', 'Total Projection for the Month INR', 'Invoiced Against Projection', 'Remarks'], axis=1) fin_data.rename(columns={'SOW No/Work Order Number': 'SOW', 'PPM id': 'PPM', 'Project Name': 'ProjName' }, inplace=True) print(fin_data) fin_data.fillna(0, inplace=True) prj_in_month = 5 inv_in_month = 6 for a in range(1, month + 1): fin_data[a] = fin_data.apply(lambda x: x[inv_in_month] - x[prj_in_month], axis=1) prj_in_month = prj_in_month + 2 inv_in_month = inv_in_month + 2 a = a + 1 The lamda function works when prj_in_month = 5 and inv_in_month = 6 , that its its takes the values in the columns ( note 5 and 6 and positions and not column names). But when the loop runs second time it gives error KeyError: (8, 'occurred at index 0') which looks to me that second time its looking for the column name 8 instead of the 8th position. I do not want to pass the column names to lamda instead i want to pass the column … -
Overwrite data in database using Django
In my project users can pay for a card, and increase their balance. I'm doing it on client-side, but can't change in database the balance field belonging to user (for users I'm using django's built in user class). So, here are my classes and scripts: models.py: class Account(models.Model): account = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) views.py: def get_webmoney(request): account_balance = Account.objects.values_list('balance', flat=True) webmoney = WebMoney.objects.all() return render(request, 'webmoney.html', {'webmoneys': webmoney, 'account_balance': account_balance[0]}) html and scripts: {% block content %} <div class="row"> {% for webmoney in webmoneys %} <div class="col-md-4 col-12"> <div class="card" style="width: 22rem; margin-bottom:30px;"> <div class="card-body"> <p class="card-text">{{ webmoney.price }} AZN</p> <button class="btn btn-primary" onclick= "let code = prompt('Please enter license number of webmoney: '); if(code == {{ webmoney.identity_code}}){ window.balance += {{ webmoney.price }}; alert('Your balance: ' + window.balance);} else {alert('Incorrect license number!')} ">Buy</button> </div> </div> </div> {% endfor %} </div> <script> window.balance = {{ account_balance }}; </script> {% endblock %}