Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - change app name in admin
I don't know how can I change name of my external app in my django admin panel. I can change verbose name of Constance app ('my constance settings'): class ConstanceConfig(AppConfig): name = 'constance' verbose_name = 'My constance settings' I don't have any idea how can I change "config" name. Any idea? -
Using python builtins to pass django request from middleware to model in order to create default model filters for current user?
I have a fairly complex django application that has been in production for over a year. The application holds data from different customers. The data is obviously in the same table, separated by customer_id. Recently the client has started to ask questions about data segregation. Since the app is sold on a per user basis and holds sensitive information, customers have been asking if and how we maintain data segregation per customer, and are there any security measures that we take to prevent data leakages (ie. data from one customer being accessed by another customer). We do our filters in the view endpoints, but eventually a developer in the team might forget to include a filter in his ORM query, and cause a data leakage So we came up with the idea to implement default filters on our models. Basically whenever a developer writes: Some_Model.objects.all() essentially they will execute: Some_Model.objects.filter(customer_id = request.user.customer_id) We plan to achieve this by overriding the objects property on each model to point to a manager with a filtered queryset. Something like this: class Allowed_Some_Model_Manager(models.Manager): def get_queryset(self): return super(Allowed_Some_Model_Manager, self).get_queryset().filter( customer_id = request.user.customer_id # the problem is that request.user is not available in models.py ) class … -
Notify user about bounced confirmation emails
My website requires users to confirm their email address they used during their registration. Therefore I send the usual confirmation email. If such a email bounces I am notified by my email provider (sendgrid). I would like to notify a user when he comes the next time to my website about the problem with his email. The notification from my email provider is an asynchron callback to some URL and I would need a way to to find the session of the user and store the information. When sending the email I could add some identifier to the request, which sendgrid would then include into the bounce message. However for some reasons I would prefer not to go this way, if possible. I would prefer to store the email address the user used in his anonymous session and use this information to later lookup his session. Is this somewhow possible? Can I add some information to an anonymous session and is this saved in the DB so I can later look it up? My Session config is the default Django configuration? -
Django 1.6: How to layout charfields in one row, without wasted space, in the admin panel
I am having a spacing issue with Django 1.6 (Python 2.7.13 x86). I have a version number in my program, and the spacing looks bad... class SoftwareAdminForm(forms.ModelForm): version1 = forms.CharField(max_length = 2, label = 'Version:', widget = forms.TextInput(attrs = {'size':2})) version2 = forms.CharField(max_length = 2, label = '.', widget = forms.TextInput(attrs = {'size':2, 'title': '.'})) version3 = forms.CharField(max_length = 2, label = '.', widget = forms.TextInput(attrs = {'size':2, 'title': '.'})) version1.initial = '0' version2.initial = '0' version3.initial = '0' So, what I want is these three char fields to look nicer, and to get rid of all the space in between; I want version1, version2, and version3 to all be flush and right next to each other. How can I do this? Thanks. Here, the first picture is how my code was rendered in part of the Admin Panel as of now... The second picture is what I am trying to achieve (I created it via paint)... -
Django form with file upload selection
I am using Django forms to load an upload form interface to the user. Here, I need to ask the user to input file name, description, and finally select a file before hitting the upload button. I am not able to get the form correct on the web page. All the labels should appear on the left and other inputs on right. But, with the below code, the choose file thing is coming on the left along with other labels which are not looking good. My understanding is that I am missing something in the forms. My code looks like this: models.py class UploadDatasetForm(forms.Form): name = forms.CharField(label='Name*', help_text='Upload button to appear only on giving a file name', max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'Please enter your dataset name'})) description = forms.CharField(label='Description (optional)', max_length=100, required=False, widget=forms.Textarea(attrs={'placeholder': 'Describe your dataset here.', 'rows': '2'})) docfile = forms.FileField(label='Choose file', help_text='only .csv', widget=forms.FileInput(attrs={'class': ''})) upload_page.html <div class="row"> <div class="col-md-7"> <div class="panel-body"> <form enctype="multipart/form-data" action="#" role="form" class="form-horizontal" method="post"> {% csrf_token %} {% for field in form %} {% if field.errors %} <div class="form-group has-error"> <label class="col-sm-2 control-label" for="id_{{ field.name }}"> {{ field.label }} </label> <div class="col-sm-10"> {{ field|attr:"class:form-control" }} <span class="help-block"> {% for error in field.errors %}{{ error }}{% … -
Avoid Parent model class creation in Django
I have the following data models: class PaymentGateway(models.Model): GATEWAYS = Choices( ('stripe', _('Stripe')), ('paybox', _('PayBox')), ('generic', _('Generic')), ) tenant = models.ForeignKey(Tenant, related_name="payment_gateways") name = models.CharField( max_length=50, verbose_name=_('Name'), choices=GATEWAYS, default=GATEWAYS.generic ) class StripeGateway(PaymentGateway): stripe_public_key = models.CharField(max_length=255) stripe_key = models.CharField(max_length=255) class Meta: verbose_name = u'Stripe Gateway' def __init__(self, *args, **kwargs): super(StripeGateway, self).__init__(*args, **kwargs) self.name = PaymentGateway.GATEWAYS.stripe def __unicode__(self): return "Stripe data for %(school_name)s" % {"school_name": self.school.name} class EtransactionGateway(PaymentGateway): pbx_site = models.IntegerField() pbx_rang = models.IntegerField() pbx_identifiant = models.IntegerField() pbx_devise = models.IntegerField() pbx_secret = models.CharField(max_length=255) class Meta: verbose_name = u'Etransaction Gateway' def __init__(self, *args, **kwargs): super(EtransactionGateway, self).__init__(*args, **kwargs) self.name = PaymentGateway.GATEWAYS.paybox def __unicode__(self): return "E-transaction data for %(school_name)s" % {"school_name": self.school.name} This is fine, but when I create an instance of either StripeGateway or EtransactionGateway, I can see another instace of PaymentGateway is created. I've tried creating the PaymentGateway abstract as suggested here but when I do this and run the migration (I already run a first migration with the current scenario) then I get an error saying something like id field in eTransactionGateway conflicts with the one from paymentGateway (sorry I can't find the trace now). For now this is ok, but I'd really like to not have instances of PaymentGateway or at … -
Is there anything I can read to learn to make a website using Django where you can search cooking recipes using the ingredients (like supercook.com)?
Is there anything I can read to learn to make a website using Django where you can search cooking recipes using the ingredients (like supercook.com)? -
Django file upload not displaying
I have written the code for file upload but it is not displaying on my destination page. Please help me edit my code or suggestions. The rest of the fields are displaying but not the file field My models.py class Help(models.Model): researcher = models.CharField(max_length=100) study = models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) document = models.FileField(upload_to='documents/', null=True, blank=True) forms.py from django import forms from .models import Help from django.forms import ModelForm class AboutHelp(forms.ModelForm): class Meta: model = Help fields = '__all__' source page <form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" name="form"> {% csrf_token %} <label>Researcher Name(s): <input type="text" name="researcher"><br> <lable>Study Summary <textarea rows="10" cols="50" placeholder="Start typing..." maxlength="500" class="form-control" name="study"></textarea> <br> <label>Upload your IRB approval letter: <input type ="file" id="irb-file" class="file_input" name="document"></label> <br> <input type = "submit" value="Submit" class="btn btn-primary" /> </form> views.py def about_experiment(request, ex_link_name): researcher = None study = None posts = None exp = get_object_or_404(Experiment,link_name = ex_link_name) high_scores = ScoreItem.objects.filter(experiment=exp,active=True) context = { 'request': request, 'exp':exp, 'high_scores': high_scores, 'awards':AwardItem.objects.filter(experiment=exp,visible=True), } if exp.about_file: context['about_file'] = settings.EXPERIMENT_DIRS+exp.about_file.get_include_path() return render(request, 'about_experiment.html', context) if request.method == 'POST': form = AboutHelp(request.POST, request.FILES) posts = Help.objects.filter().order_by('-date')[0] if form.is_valid(): obj = form.save(commit = False) obj.save() researcher = form.cleaned_data['researcher'] study = form.cleaned_data['study'] document = form.cleaned_data['document'] else: form = AboutHelp() … -
Django: ID Null after Save
I Got this Models in models.py: class Boats(models.Model): id = models.BigIntegerField(primary_key=True) created = models.DateTimeField(default=timezone.now, blank=True) name = models.CharField(max_length=30) class Meta: managed = True db_table = 'boats' ordering = ['name'] class Clients(models.Model): id = models.BigIntegerField(primary_key=True) created = models.DateTimeField(default=timezone.now, blank=True) code = models.CharField(max_length=100) class Meta: managed = True db_table = 'clients' ordering = ['name'] ========================== In the views.py; my function do it like that: f = NewBoatForm(request.POST) if f.is_valid(): nBoat = f.save() print 'ID:'+str(nBoat.id) cBoat = ClientsBoats() cBoat.client = client cBoat.boat = nBoat cBoat.save() But django fails with this error: ValueError: save() prohibited to prevent data loss due to unsaved related object 'boat'. I print the ID but it's Null. Can someOne help me. -
How to do a filtered aggregate with Django's ORM
I have a Django model like: class Post(models.Model): name = models.CharField(max_length=10) class Topic(models.Model): name = models.CharField(max_length=10) class Annotator(models.Model): post = models.ForeignKey(Post, related_name='annotations') topic = models.ForeignKey(Topic) name = models.CharField(max_length=10) How do I find all Post records that don't have an associated Annotator record with a specific topic and Annotator name value? Without the topic and name filtering criteria, the Django query would look like: qs = Post.objects.all() qs = qs.annotate(annotations_count=Count('annotations')) qs = qs.filter(annotations_count=0) but what I want to do would be something like: qs = Post.objects.all() qs = qs.annotate(annotations_count=Count('annotations' where name='annotator1' and topic='topic1')) qs = qs.filter(annotations_count=0) which obviously isn't legal. I'm currently using .raw() to perform a traditional LEFT OUTER JOIN so I can do this filtering in the WHERE clause, but this prevents me from re-using a lot of code and filters I've rewritten using the Django ORM. How do you add filtering criteria to Django's .annotate() method, or otherwise achieve the same result? I'm using Django 1.11. -
django ModelChoiceField set queryset from views.py
I am new to django, need some help. forms.py import floppyforms as ff from django import forms from django.contrib.auth.models import User from .models import Prodavnica, Racun, Transakcija ... class IzdatakForm(forms.ModelForm): izdatak = forms.DecimalField(max_digits=20, decimal_places=2, widget=forms.NumberInput(attrs={'min': '0', 'step': '0.01'})) datum = ff.DateField(widget=ff.DateInput(format='yyyy-mm-dd')) vreme = ff.TimeField(widget=ff.TimeInput(attrs={'step': '60'}, format='HH-MM')) prodavnica = forms.ModelChoiceField(required=True,queryset=Prodavnica.objects.all()) class Meta: model = Transakcija fields = ['izdatak', 'datum', 'vreme', 'racun', 'prodavnica'] models.py from django.contrib.auth.models import User from django.db import models from django.urls import reverse # Create your models here. class Prodavnica(models.Model): author = models.ForeignKey(User, on_delete=models.PROTECT) naziv = models.CharField(max_length=50, unique=True, blank=False) adresa = models.CharField(max_length=200, blank=True) telefon = models.CharField(max_length=50, blank=True) foursquare = models.URLField(blank=True) def get_absolute_url(self): return reverse(viewname='finance_detail_shop', kwargs={'pk': self.pk}) def __str__(self): return self.naziv class Transakcija(models.Model): korisnik = models.ForeignKey(User, on_delete=models.PROTECT) suma = models.DecimalField(max_digits=20, decimal_places=2, default='0.0') izdatak = models.DecimalField(max_digits=20, decimal_places=2, default='0.0', null=True) dodatak = models.DecimalField(max_digits=20, decimal_places=2, default='0.0', null=True) prodavnica = models.ForeignKey('Prodavnica', related_name='prodavnica', blank=True, null=True) racun = models.ForeignKey('Racun', related_name='Racun') datum = models.DateField() vreme = models.TimeField() def get_absolute_url(self): return reverse(viewname='finance_detail_transaction', kwargs={'pk': self.pk}) def __str__(self): return '%s %s (%s %s)' % (self.pk, self.suma, self.datum,self.vreme) class Racun(models.Model): vlasnik = models.ForeignKey(User, on_delete=models.PROTECT, related_name='vlasnik') ovlacena_lica = models.ManyToManyField(User, related_name='ovlaceno_lice') naziv = models.CharField(max_length=50, unique=True) broj = models.IntegerField(unique=True) def get_absolute_url(self): return reverse(viewname='finance_detail_account', kwargs={'pk': self.pk}) def __str__(self): return self.naziv views.py class TransakcijaDodatakCreate(CreateView): model = … -
Django-Haystack - Searching in specific fields
I am using Django-Haystack with Solr for search. Currently my search engine works fine but only targets the id or django_id field. However, I do only want to target the title and/or body field when searching for results. I have followed the Django and Django-Haystack tutorial. Debugging was needed to make Django-Haystack work with Solr 6. I have tried lots of things, but none of them resolved this issue. Versions: Django: 1.11.3 Django-Haystack: 2.6.1 Pysolr: 3.6.0 Solr: 6.6.0 The configuration of the main files: notes/models.py: from django.db import models class Note(models.Model): title = models.CharField(max_length=200) body = models.CharField(max_length=200) def __unicode__(self): return self.title def __str__(self): return self.title notes/search_indexes.py: import haystack from haystack import indexes from .models import Note class NoteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title') body = indexes.CharField(model_attr='body') def get_model(self): return Note def index_queryset(self, using=None): return self.get_model().objects.all() notes/templates/search/indexes/notes/note_text.txt: {{ object.title }} {{ object.body }} After I made the core (named: default), I changed managed-schema to schema.xml in the Solr core configuration folder. I ran ./manage.py build_solr_schema and copied the following fields to schema.xml: <field name="body" type="text_en" indexed="true" stored="true" multiValued="false" /> <field name="text" type="text_en" indexed="true" stored="true" multiValued="false" /> <field name="title" type="text_en" indexed="true" stored="true" multiValued="false" /> I did also add the … -
import asgi_redis: ImportError: No module named _compat
I can import asgi_redis on my local server fine but I get the error in the title when i try to import asgi_redis on my production server (heroku, using heroku run bash). Both have the same version of asgi_redis. Here is the full traceback: >>> import asgi_redis Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/app/.heroku/python/lib/python2.7/site-packages/asgi_redis/__init__.py", line 1 , in <module> from .core import RedisChannelLayer File "/app/.heroku/python/lib/python2.7/site-packages/asgi_redis/core.py", line 10, i n <module> from redis._compat import b ImportError: No module named _compat Does anyone know what is going on here? Thanks in advance. I also have redis installed, redis 2.6.0, FWIW -
How to show form this query in django
I have two django models: class RegistrationDetail(models.Model): registration_number = models.CharField( _("Registration Number"), max_length=32, unique=True, db_index=True) policies = models.ManyToManyField('Policy', blank=True) class Policy(Models.model): policy_id = UUIDField(unique=True) issue_date = models.DateTimeField(null=True) start_date = models.DateField() expiry_date = models.DateField() I have to form a query which finds out all the policies attached to respective registration numbers and then compares if the start dates of the corresponding policies of a particular registration number have a difference of 300 days or not. How do i proceed with this query ? -
Putting a click event for a dialogue box with Django Tables2
I am trying to make a click event with Django Tables2 so that whenever someone clicks on a delete link in a row it will create a dialogue box for confirmation before deleting the row. Here is my code: models.py class Schedules(models.Model): course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus') location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield') room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A') start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today) start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am') end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am') instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale') total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six') hours_per_class = models.CharField(max_length=128, choices=HOURS_PER_CLASS_CHOICES, default='four_and_half') frequency = models.CharField(max_length=128) status = models.CharField(max_length=128, choices=STATUS_CHOICES) interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day') initiated_by = models.CharField(max_length=128, null=True) schedule_id = models.IntegerField(default=0) tables.py class ScheduleListTable(tables.Table): change = tables.TemplateColumn('<a href="/schedule/update_schedule/{{ record.id }}">Update</a> / Cancel / Event / ' '<a href="/schedule/delete_schedule/{{ record.id }}" onclick="return confirm("Are you sure you want to delete this?")">Delete</a>', verbose_name=u'Change', ) class Meta: model = Schedules fields = ('id', 'course_name', 'start_date', 'start_time', 'hours_per_class', 'instructor', 'change',) attrs = {"class": "paleblue"} views.py def schedule_List(request): context_dict = {} schedule_list = Schedules.objects.order_by('start_date') table = ScheduleListTable(schedule_list) context_dict['table'] = table return render(request, "schedule/schedule_list.html", context_dict) schedule_list.html <div id="schedule_list_table"> {% if table %} {% render_table table %} {% endif %} </div> For some reason, I can't make the onclick event … -
Django python iteration through a query set error
The code that is giving me the problem pk = request.POST['pk'] medrec = MedicalRec.objects.get(pk=pk) med = Medicine.objects.filter(medicalrec=medrec) for f in med: print("med check") print(f.pk) print(f.stockpk) for ed in med: print("printing dtock") print(ed.stockpk) print("end of doc") a= pks() a.pk = ed.stockpk a.count = request.POST[str(ed.pk)] ls.append(a) for l in ls: print(l.pk) print(l.count) for n in ls: s= Stock.objects.get(pk=n.pk) print(s.name) s.quantity = s.quantity- int(n.count) s.save() return redirect('/billing') Output med check 3 1 med check 4 2 med check 5 3 3 printing dtock 1 end of doc printing dtock 2 end of doc Internal Server Error: /mbill/ Traceback (most recent call last): File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\datastructures.py", line 83, in __getitem__ list_ = super(MultiValueDict, self).__getitem__(key) KeyError: '4' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 42, in inner response = get_response(request) File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Develop\web\ayur\main\views.py", line 136, in mbill a.count = request.POST[str(ed.pk)] File "C:\Users\Deep\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'4'" I am not able to find the error. The iteration just stops in the middle. The same med query set gives until output until 3 but … -
Trying to figure out reason for 400 error in post testing Django-Rest-Framework API
Here is the model that I am testing: class Entity(TimestampModerated): name = models.CharField(max_length=255) slug = models.SlugField(unique=True) description = models.TextField(verbose_name='description of entity', blank=True) media = models.URLField(verbose_name='media representing entity (image, mp3, mpg, etc)', blank=True, null=True) uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4(), editable=False, ) owner = models.ForeignKey('auth.User', related_name='entities', on_delete=models.CASCADE) tags = TaggableManager(blank=True) def get_absolute_url(self): return reverse('entities:detail', kwargs={'slug': self.slug}) def __str__(self): return self.name class Meta: verbose_name_plural = "entities" Here is the ViewSet: class EntityViewSet(viewsets.ModelViewSet): """ This viewsetomatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = Entity.objects.all() serializer_class = EntitySerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) lookup_field = 'slug' def perform_create(self, serializer): serializer.save(owner=self.request.user) Here are my urls: router = DefaultRouter() router.register(r'entities', views.EntityViewSet) router.register(r'users', views.UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), ] Here is my test: class EntitiesAPITests(test.APITestCase): def setUp(self): test_user = models.User.objects.create(username='testuser', password='password') def test_login_post(self): client = APIClient() client.login(username='testuser', password='password') response = client.post('/api/entities/', data={ 'name': 'Sean Penn', 'slug': 'sean-penn' }) self.assertContains(response, 200) client.logout() When I run the tests I get the following error, which I haven't been able to figure out: ====================================================================== FAIL: test_login_post (entities.tests.test_api.EntitiesAPITests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/xxx/xxx/entities/tests/test_api.py", line 63, in test_login_post self.assertContains(response, 200) File "/Users/xxx/xxx/.virtualenv/lib/python3.6/site-packages/django/test/testcases.py", line 385, in assertContains response, text, status_code, msg_prefix, … -
reportlab: how to set initial/default view?
I've managed to successfully generate an empy PDF, but it doesn't set the initial view. I'd like to set the initial view to "full view" i.e. the end user see one page fits the PDF reader (= an A4 page fits in the screen). def render_to_response(self, context, **response_kwargs): response = HttpResponse(content_type='application/pdf; charset=utf-8') response['Content-Disposition'] = 'attachment; filename=""' p = canvas.Canvas(response, pagesize=A4, ) p.showPage() p.save() return response How to set the default zoom view (if it's possible) with reportlab? -
Extending User Profile
Please i need help .I have a problem in extending userprofile.At first everything seems to be working good until now .Please i need help in resolving this bellow is my code . Model.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile") date =models.DateField(blank=False,null= True) bio = models.TextField(max_length=500,blank=False) picture = models.ImageField(upload_to="profile_image",null=True,blank=True) company = models.CharField(max_length=500,null=True) def __str__(self): return self.user.username @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save,sender=User) def save_user_profile(sender,instance,**kwargs): instance.UserProfile.save() views.py ` def update_profile(request): if request.method == 'POST': profile_form = ProfileForm(request.POST,request.FILES,instance=request.user.userprofile) if profile_form.is_valid(): profile_form.save() messages.success(request,'Your Profile has been Updated') return redirect('success:profile_account') else: messages.error(request,'fill out the fields correctly') else: profile_form = ProfileForm(instance=request.user.userprofile) return render(request,"success/user_account/edit_profile.html",{'profile_form':profile_form}) html.form <form action='{{ action_url }}' method="post" enctype="multipart/form-data"> {% csrf_token %} {{ profile_form.bio}}{{profile_form.bio.error}} {{ profile_form.picture}}{{profile_form.picture.error}} <div class="pc"><label>Company Name:</label>{{ profile_form.company}}{{profile_form.company.error}} {{ profile_form.date}}{{profile_form.date.error}} <button type="submit">Save changes</button> Error I get Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each … -
Tag elements in an webpage and then show only the elements based on a the tags that the user selects
I would like to create a website that would allow me to tag some elements. Lets have this example. I have this following element: "This is a text" and I would like to tag it with the tag text. Then I would put all the possible tags on the side of the webpage and when a user select one or multiple tags to show the elements that contain that tag. Does anyone has in mind any tool that can help in achieving such thing? A real example is the https://www.overleaf.com/dash site. I would like to do the exact thing. Thank you! -
Dkango render img
How can I transfer a picture without saving it? views.py import qrcode img = qrcode.make('Some data here') #img.save("")Saving a picture to disk return render(request, 'home.html','img':img) home.html {% block content %} <img {{ img }}> {% endblock %} Is it possible? -
When to choose a certain Back-End framework? [on hold]
My question is pretty simple, I have seen a lot of comparisons between different Back-End frameworks, and also read a lot of articles about pros and cons of each of these frameworks individually.. But I couldn't find a simple answer to my question.. When should I use Laravel, Django, Rails, Express and ASP.NET? And I want the answer to be only from the perspective of the type of the App. So from what I heard, let's say that I want an App that will include a lot of real-time functionality, so in this situation Express would be the most suitable (correct me if I'm wrong). And also from what I heard, if your App gonna need a lot of scalability (Talking about millions of requests per second), then don't go with Rails (ps: I heard that now there are some solutions for this specific problem in Rails). So if anyone could tell me which type of application is preferred to be built with which framework, that would be GREAT! Or if my question is wrong in the first place, I would be so grateful to be enlightened with a correct perspective. PS: I'm asking this question because I just started … -
Django Testing - loading data into the database before loading the apps
I'm currently writting some tests for a Django app (+ REST framework), and having some issues loading the test data into the database. Let me explain with some (very simplified) code : I have a django view which is something like : view.py from myapp.models import Item from myapp.utils import MyClass # need to initialize with the set of items item_set = {item.name for item in Item.objects.all()} my_class_object = MyClass(item_set) class MyView(APIView): def post(selfself, request): result = my_class_object.process(request.data) return Response(result) So basically I need to initialize a class with some data from the database, and I then use this class in my view to process the data received by the endpoint. Now the test : my_test.py from rest_framework.test import APILiveServerTestCase from myapp.models import Item class MyTest(APILiveServerTestCase): def setUp(self): self.URL = '/some_url_linking_to_myview/' # load some data Item.objects.create(name="first item") Item.objects.create(name="second item") def test_myview_return_correct_result(self): post_data = {"foo"} response = self.client.post(self.URL, data=post_data, format='json') self.assertEqual(response.status_code, 200) self.assertEqual(response.data, {"my_expected_result"}) When running the test, what currently happens is that view.py is loaded before the setUp() method get excecuted, so when I instantiate the class with these two lines : item_set = {item.name for item in Item.objects.all()} my_class_object = MyClass(item_set) the database is still empty. I'm wondering if … -
Add and delete Celery periodic tasks at runtime
I've been battling with this task all day. I have a Django app. I use Celery for asynchronous tasks. Occasionally, I want to create a periodic task. The number of times that tasks will run unknown, but it will need to be deleted later. So the task could be like this: @shared_task def foobar_task(id): if this_should_run: do_task() else: PeriodicTask.objects.get(name='{} task'.format(id)).delete() My app is running. I have celery beat running in a Docker container, run using using celery --app=myproject beat --loglevel=info --scheduler=django. I have another container running the standard celery worker. So now I want to dynamically create my periodic task. I have a view/API endpoint that triggers something like this: schedule, _ = IntervalSchedule.objects.get_or_create(every=15, period=IntervalSchedule.SECONDS) PeriodicTask.objects.create(interval=schedule, name='{} task'.format(id), task='myapp.tasks.foobar_task') In the Django admin, I can see the periodic task has been created. However, watching the logs for both the celery container and celery beat container, nothing happens. Why is celery beat not picking up that there's a new periodic task? I don't want to have to restart celery beat every time a new task is created or deleted. Note: I am using Django 1.11.2, PostgreSQL, Celery 4.0.2, Django Celery Beat 1.0.1. -
Django template queryset.example_set.all() showing different primary key
{% for n in medrec %} <tr> <td>{{ n.patient.pk }}</td> <td>{{ n.patient.name }}</td> <td> <div class="ui grid"> <form class="ui form" id="mform{{ n.id }}" action="/mbill/" method="post"> {% csrf_token %} <input value="{{ n.pk }}" type="hidden" name="pk"> {% for m in n.med_set.all %} <div class="row"> <div class="eight wide column">{{ m.medicine }}</div> <div class="eight wide column"> <div class="field"><input name="{{ m.medicine.id }}" type="text"></div> <h5>{{ m.medicine.quantity }} left</h5> </div> </div> {% endfor %} </form> </div> </td> <td class="right aligned"> <button type="submit" class="ui button green" form="mform{{ n.id }}" id="mbill">bill</button> </td> </tr> {% endfor %} I am trying to access pk of foreign keys of medrec or n. but instead of real pk it show 1,2,3... every time the n.medicine.id gives 1,2,3... instead of the real 3,4,5 is there a work around for this? class Medicine(models.Model): medicalrec = models.ForeignKey(MedicalRec,related_name='med_set') medicine = models.ForeignKey(Stock,related_name='stock_set') stockpk = models.IntegerField() class MedicalRec(models.Model): patient = models.ForeignKey(Patient) date = models.DateField() disease = models.TextField() treatment = models.TextField() billed = models.BooleanField()