Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I transfer context variable into a html bound javascript code in Django ?
I have write down a view: def Country_names(request): c_list = [] for c_name in c_names: c_list.append(c_name) return render(request, 'DATAPLO/Country_list.html', {'c_list':c_list}) This view transfers a list/array to template further in my html template it try to convert this python variable into javascript array variable. <script> //variable defined to store "c_list" array var c_names = {{c_list}} //try to access array items like this c_names[0] </script> But his method is not working in my case how can I do this, I have explore few similar threads on the web but nothing is working in my case. thanks -
Django file upload not correctly decoding
I have form through which i am uploading a file at the respective experiment's attachment folder. The file is being correctly uploaded but the contents are lost. Also when i open the PDF it says not correctly decode. How do i solve this issue? views.py def about_experiment(request, ex_link_name): researcher = None study = 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 request.method == 'POST': pi_obj = PrincipalInvestigator.objects.get(user=request.user) form = AboutHelp(request.POST, request.FILES) if form.is_valid(): file_path = settings.EXPERIMENT_DIRS + str(exp.id) + "\\" + "attachment" + "\\" + str(request.FILES['irb_file']) researcher = form.cleaned_data['researcher'] study = form.cleaned_data['study'] upload_irb_file(file_path) file_var1 = "about_"+ exp.name file_name1 = "about_" + exp.name + ".html" try: att = Attachment.objects.get(experiment=exp, name=file_var1, ext="html") att.versions = att.versions + 1 att.version = att.versions att.save() AttachmentEdit.objects.create(attachment=att, version=att.version, pi=pi_obj,tag=att.experiment.current_tag) except Attachment.DoesNotExist: att = Attachment.objects.create(experiment=exp, name=file_var1, ext="html", filetype=getFileType(file_name1)) AttachmentEdit.objects.create(attachment=att, version=att.version, pi=pi_obj, tag=att.experiment.current_tag) create_file(exp, att.get_current_version(), researcher, study) exp.about_file = att exp.save() #copyfiles(exp, a, att.get_current_version()) #os.remove(a) return HttpResponseRedirect('/about/%s/' %ex_link_name) else: if exp.about_file: context['about_file'] = settings.EXPERIMENT_DIRS + exp.about_file.get_include_path() return render(request, 'about_experiment.html', context,) Def for form upload def upload_irb_file(filename): with open(filename, 'w+') as destination: for chunk in destination: destination.write(chunk) destination.close() form <form class ="form-group" action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST" … -
Convert json string data back into python image object
The code below get's image data from a form, and then converts so it can be json serializable. I want to show the image on the html template by converting the image data into base64, however i need to convert the json data (string) back into a python image object / data. View def View1(request): form = FormFile(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): image = request.FILES.get('image').read() request.session['image_file'] = json.dumps(str(image)) return redirect('View2') template = 'view1.html' context = { 'form': form, } return render(request, template, context) def View2(request): img = request.session.get('image_file') # this is the json data that needs to be converted back into python image object img_temp = NamedTemporaryFile() img_temp.write(img) img_temp.flush() img = Image.open(img_temp) img_format = img.format img.close() with open(img , "rb") as imageFile: encode_image = base64.b64encode(imageFile.read()) form = FormCreate(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): instance = form.save(commit=False) instance.image.save(img_format , File(img_temp), save = True) instance.save() template = 'view2.html' context = { 'encode_image': encode_image, 'img_format': img_format, } return render(request, template, context) Template (View1) <form method="POST" enctype="multipart/form-data"> {{ form.image }} # form image input </form> Template (View2) <img src="data:image/{{ img_format }};base64, {{ encode_image }}"></img> -
How to query previous items of a given criteria
Here is the model class Player(models.Model): name = models.CharField() class ShootingAttempt(models.Model): player = models.ForeignKey(Player, related_name='shooting_attempts') is_scored = models.BooleanField() point = models.IntegerField(default=0) created_at = models.DateTimeField(auto_add_now=True) The implementation: jordan = Player.objects.create(name='Michael Jordan') attempt1 = ShootingAttempt(player=jordan, is_scored=False) attempt2 = ShootingAttempt(player=jordan, is_scored=False) attempt3 = ShootingAttempt(player=jordan, is_scored=True, point=3) attempt4 = ShootingAttempt(player=jordan, is_scored=False) attempt5 = ShootingAttempt(player=jordan, is_scored=True) attempt6 = ShootingAttempt(player=jordan, is_scored=True, point=3) Now how can i query the previous is_scored=False if a given ShootingAttempt where pk=5 assumed for attempt5 by Player named Micheal Jordan? This will yield the result of: [attempt4] If the given ShootingAttempt where pk=3 (attempt3) this will return [attempt1, attempt2] Is there any work around? -
list indices must be integers, not str , when assigning query string to field in forms
I am getting a variable from view and then modifying in function later like this class labelModelForm(forms.ModelForm): model = Labels_tool_ fields = ['apn', 'owner_name', 'situs_addr_One', 'situs_addr_Two', 'mailing_addr_One', 'mailing_addr_Two'] apn = forms.ModelChoiceField(queryset=Field.objects.values_list('name', flat=True), empty_label="(Choose field)") def __init__(self, *args, **kwargs): //getting layer_id from views layer_id = kwargs['layer_id'] print layer_id layer=Layer.objects.filter(id=int(str(layer_id))).first() x=Field.objects.filter(layer=layer) //On this step when modify queryset I get error self.fields['apn'].queryset= Field.objects.filter(layer=layer) When I do this I get the error 'list indices must be integers, not str ' . So how can I modify my query set ? -
Django login error and cannot login
I try to find a similar question but I did not find the answer what I want. I am new to Django, I was trying to learn about authentication in Django but I got an error like this: AttributeError: 'AnonymousUser' object has no attribute '_meta' Here is my code: views.py def login(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = request.GET['username'] password = request.GET['password'] user = authenticate(username=username, password=password) if user is not None: login(request,user) return redirect('/') else: error = " Sorry! Username and Password didn't match, Please try again ! " return render(request, 'girl/login.html',{'error':error}) else: form = LoginForm() return render(request, 'girl/login.html', {"form":form}) forms.py class LoginForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password') login.html {% extends 'base.html' %} {% block content %} <h1>Login</h1> {% if error %} {{ error }} {% endif %} <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" value="login"> </form> {% endblock %} Any help would be appreciated. Thanks! -
django - How to iplement jwt in micro services
I'm new in jwt and microservices. Can anyone give me a simple practice of authentication by Json web token between microservices in 2 scenarios: - Share secret key all services. All services can verify token on their own. - Authentication via one authentication services. -
Django query to Sum the lengths of ArrayFields
I have this model: class Interation(models.Model): user = models.ForeignKey(User) codes = ArrayField(models.CharField(choices=CODE_CHOICES)) and I'm trying to figure out how to do the equivalent of this SQL query in Django: select user_id, sum(cardinality(codes)) from interaction group by user_id; (I ruled out raw SQL because there are a lot of WHERE statements I left out which make this query difficult to reconstruct by hand.) I tried extra(select={codes_len':'cardinality(codes)'}), but you cannot annotate or aggregate over an extra field. I tried annotate(Sum("cardinality('codes')")), but cardinality('codes') isn't a field on the model. I investigated writing a custom aggregate field that combined Sum and cardinality, but that looked... brittle. I discovered in the docs that __len does work properly on an ArrayField, but not in the context of annotate(Sum('codes__len')). At this point I think I have no other choice but to add a field to the model that is the length of the codes field and mess with save() to keep it in sync. Is there really no other way? Am I missing something? -
Error while accessing a variable in jinja2
I'm using Jinja2 with django framework, I'm getting data into dictionary from views.py by the name 'content', then I have to print this jinja snippet in a table, so I need the length of each list in 'content', but the jinja variable's scope is not global . Here is jinja snippet : {%extends "webEs/index.html"%} {%block content%} {%set n = 0 -%} {%for a in content%} {%set n = {{a|length}} %} {%endfor%} {%for i in range(n)%} <tr> {%for c in content%} <td>{{c[i]}}</td> {%endfor%} </tr> {%endfor%} {%endblock%} Please help me get my requirement fulfilled. -
Why can't I access beaglebone black board when channels in INSTALLED APPS?
I had a webserver use django on beaglebone black. And I use channels layer asgi_ipc as a websocket to sent ping pong signals. I still can access when I disabled channels in INSTALLED APPS, but I can't when I enabled it. -
Og tags keep showing home page info
I have added og tags on my products page. it should show product title, description and image when i post individual product on facebook. But it always shows home page title, description and default website image. can anyone help me tell me what is the mistake ? am using django based website. -
new django/python user having issues with __init__ i've defined a few classes, and want to use one class as a field for another
I'm a new django user and am confused by some features of inheritance and instantiation, particularly making a field of a type class that is user defined. When I try to add an artist from the admin page i get python TypeError: init() missing 5 required positional arguments: 'name', 'first_name', 'last_name', 'website', and 'instagram' [18/Jul/2017 21:43:28] "GET /admin/showyourwork/artist/add/ HTTP/1.1" 500 110559 from django.db import models # Create your models here. from django.db.models import ImageField from django.urls import reverse class Artist(models.Model): # Fields first_name = models.CharField(max_length=30, null=True) last_name = models.CharField(max_length=30, null=True) name = models. CharField(max_length=61, null=True) website = models.CharField(max_length=50, null=True) instagram = models.CharField(max_length=20, null=True) # Metadata class Meta: ordering = ["last_name", "first_name"] # Methods def __init__(self, name, first_name, last_name, website, instagram): self.name = name self.first_name = first_name self.last_name = last_name self.website = website self.instagram = instagram def get_absolute_url(self): """ Returns the url to access a particular instance of MyModelName. """ return reverse('model-detail-view', args=[str(self.id)]) def __str__(self): """ String for representing the MyModelName object (in Admin site etc.) """ return self.name class Media(models.Model): # Fields title = models.CharField(max_length=50) artist = models.ForeignKey(Artist) # Metadata # class Meta: # ordering = ["author", "title"] # Methods def __init__(self, title): self.title = title self.artist = Artist(None, None, … -
Django Generic View Model Filtering
so basically i have this generic view that inherits from ListView and what i want it do to is to take some sort of argument (like a string or "options") and then filter my model depending on those arguments. I've looked for two days and can't seem to find much about this. I've played around with overwriting the get_queryset function also just tried filtering in directly like so: model = product.objects.filter(pk__in=[1,2,3,4,5]) however most of the times it just gives me this error: /python3.5/site-packages/django/views/generic/list.py", line 38, in get_queryset queryset = self.model._default_manager.all() AttributeError: 'QuerySet' object has no attribute '_default_manager' I don't really need an "solution" i'd be just fine if someone just could point me to where i can read in deapth about this since i've only managed to find basic description. Thanks -
How to connect the Angular js with Django using Pycharm
I am using django in Pycharm IDE. How to connect with Angular js and django in Pycharm IDE? -I used choclatey and installed node.js. -
Advance GPS manipulation in django and python
I have thought of how to create a web project that helps locate a fellow user and helps trace routes in locating and estimations with other similar features like UBER has but I dont have a clue on how to build such a feature. I would be glade if someone points me to places where I can find help and necessary resources to learn and build this awesome app. Thanks for your help. -
Django post_save signal can not get model properties
I have a function: @receiver(post_save, sender=Order) @Tool.disable_for_loaddata def post_save_order(sender, instance, created, **kwargs): if created: send_email_notify_ordered(to_address="example@gmail.com", full_name=order.customer.username, order_cost=order.total_cost), prepaid=order.prepaid) In that code: total_cost is a model's property. But i get 0.0 from here. If i call an instance of Order model: order = Order.objects.get(pk=order_id) order.total_cost return needed data normally Something wrong with me? Sorry for bad English. -
Poor performance when calculating averages
I need to show averages of offer prices. The problem is that I have to calculate the averages for combinations of a many-to-many field. I also have to page all this. I already did it. The problem is that it has a poor performance, and I'm looking for a way to solve it. The model looks like this: class Offer(models.Offer): price = DecimalField(max_digits=10, decimal_places=2) quantity = PositiveIntegerField() product = ForeignKey(Product) qualifiers = ManyToManyField(Qualifier) The relevant code to calculate the averages is this: def get_average(product, qualifiers): offers = Offer.objects.filter(product=product) for qualifier in qualifiers: offers = offers.filter(qualifiers=qualifier) if not offers.count(): return None offers = offers.aggregate( quantity_x_price_sum=Sum(F('quantity') * F('price'), output_field=FloatField()), quantity_total=Sum('quantity') ) # Weighted average return offers['quantity_x_price_sum'] / offers['quantity_total'] def get_averages(products): averages = [] for product in products: colors = product.qualifiers.filter(type=1) sizes = product.qualifiers.filter(type=2) other = product.qualifiers.filter(type=3) qualifiers = [colors, sizes, other] combinations = list(itertools.product(*qualifiers)) for combination in combinations: average = get_average(product, combination) if average is not None: averages.append(average) Any help will be welcome. Thanks. -
Consume a third-party API protected with Oauth2 in Django
I am trying to access a third-party API with my Django app to post some information to that API. This API supports OAuth2 authentication only and I am trying to build a Oauth2 client of consume an existing library. I found lots of solutions to implement an Oauth2 server (which is not what I needs) and some solutions to enable Oauth2 login in Django (which is not what I need either). Could anyone please point me to the right direction? -
How can I implement a communication system within my django web application
I am developing a platform in django and im having a hard time searching a way to implement a communication (ex. Chat, messaging, email) system within the users of my platform. -
Django 1.11 admin Invalid field name(s) given in select_related
In the Django Admin documentation about select related, the code example specifies that declaration of list_select_related = ('authors', ) will help to prevent N+1 issues. I am attempting to use this with a set of models as defined below: class Grouping(models.Model): name = models.CharField(max_length=128, null=False) class InsightCondition(models.Model): criterion = models.CharField(max_length=256, db_index=True) description = models.CharField(max_length=256, db_index=True) class Insight(models.Model): my_other_thing = models.CharField(max_length=128, null=False) grouping = models.ForeignKey('Grouping', related_name="insights", blank=False, null=False) condition = models.ForeignKey('InsightCondition', related_name='insights', null=True, blank=True) When attempting to use the Django admin declrations, I still see the n+1 issue in the log. In order to fix this, I add the list_select_related = ('insights', ) to the following class: @admin.register(Insight) class InsightAdmin(admin.ModelAdmin): list_display = ('condition_link', 'uid', 'grouping_link', 'detail_description', 'state', ) list_filter = ('grouping', 'condition') list_select_related = ('grouping', 'condition') grouping_link = easy.ForeignKeyAdminField('grouping') condition_link = easy.ForeignKeyAdminField('condition') pass @admin.register(Grouping) class GroupingAdmin(admin.ModelAdmin): list_display = ('name', 'insight_count') search_fields = ['name', 'insights__uid'] list_select_related = ('insights', ) def insight_count(self, group): return group.insights.count() pass @admin.register(InsightCondition) class InsightConditionAdmin(admin.ModelAdmin): list_display = ('criterion', 'description', ) search_fields = ('criterion', 'description', ) # Failing Lines .... list_select_related = ( 'insights', ) select_related = ('insights', ) pass When loading on the admin site, I get the error FieldError at /admin/insights/insightcondition/ Invalid field name(s) given in select_related: 'insights'. … -
Django form for each item in a list
I am trying to make a webapp using django that allows the user to choose who they believe the winner will be in a couple of games. I have the games as a model that has the home team, away team, id, among other things. Now on submit I would like the users to insert multiple rows into a table that has the user id and the team they have selected. I have tried using formsets, but I can't figure out how they work with different labels. The form I currently have is this. class PickForm(forms.ModelForm): ''' A form that allows a user to make a pick on the selected game ''' error_messages = { 'no_match': ('Your selections do not match the corresponding options') } team_picked = forms.CharField(label=('Your choice')) class Meta: model = Pick fields = ('team_picked',) def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id', None) self.matchweek = kwargs.pop('matchweek', None) super(PickForm, self).__init__(*args, **kwargs) def clean_team_picked(self): team_picked = self.cleaned_data['team_picked'] if(team_picked == self.home_team): return team_picked elif(team_picked == self.away_team): return team_picked else: raise forms.ValidationError( self.error_messages['no_match'], code='no_match', ) def save(self, commit=True): pick = super(PickForm, self).save(commit=False) pick.team_picked = self.cleaned_data['team_picked'] pick.user_id = self.user_id pick.matchweek = self.matchweek if commit: pick.save() return pick Thanks! -
How to send a body in Swagger Django documentation?
I try to use Swagger documentation in my Django project however I am not able to send body. Furthemore, List Operations doesn't work. Anyone have an idea how to fix it? I have only default settings: urls.py: from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Title API') urlpatterns = [ url(r'^swagger', schema_view), ] I can only list all my URLs and log in as admin. Logout doesn't work. At this moment when I choose Expand Operations I see something like this: -
Reading data from mysql database into a dictionary in python
Earlier I was reading an excel file and storing it into a dictionary as follows: def read_data(xls): book = xlrd.open_workbook(xls) sheet = book.sheet_by_index(0) bank_acct_num=[] d={} vendor_name=[] for row_index in xrange(1, sheet.nrows): # skip heading row col1, col2, col3, col4, col5 = sheet.row_values(row_index, end_colx=5) bank_acct_num.append(col2) vendor_name.append(col3) col2 = unicode(col2).encode('UTF8') col3 = unicode(col3).encode('UTF8') d.setdefault(col2, []) d[col2].append(col3) del d[''] #print(d) return d If the table is like this: Id | Name 1 | Name1 1 | Name2 2 | Name3 2 | Name4 then the output of the dictionary d is like this: {'1': ['Name1', 'Name2'], '2': ['Name3', 'Name4'],..} Now, instead of reading from the excel file, I put this excel file database into a mysql db. Now, I'm using Django to read data from the database onto the webpage. My models.py is as follows: from django.db import models # Create your models here. class my_table(models.Model): col1 = models.CharField(max_length = 80) col2 = models.CharField(max_length = 80) col3 = models.CharField(max_length = 200) col4 = models.CharField(max_length = 20) col5 = models.CharField(max_length = 20) id = models.IntegerField(primary_key=True) My views.py is as follows: def display(request): return render_to_response('template.tmpl', {'obj': models.my_table.objects.all()}) And I'm displaying the table. Now, what I really want is to be able to get the dictionary … -
Django compressor not converting images to data URIs
I'm having issues setting up replacing of URLs with data URIs with django compressor. Here are relevant settings: STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static'), os.path.join(BASE_DIR, 'foo', 'bar'), os.path.join(BASE_DIR, 'foo', 'baz'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = os.environ.get('STATIC_FILE_URL', '/static/') CSS_INCLUDE_PATHS = '.:{foo}'.format(growth=os.path.join(BASE_DIR, 'foo')) LESSC_COMMAND = 'node_modules/.bin/lessc {include_paths} {{infile}} {{outfile}} --autoprefix="> 1%"'.format( include_paths="--include-path='{paths}'".format(paths=CSS_INCLUDE_PATHS) ) COMPRESS_PRECOMPILERS = ( ('text/less', LESSC_COMMAND), ('text/javascript', 'node_modules/.bin/rollup {infile} -c rollup.config.js --output {outfile}'), ) COMPRESS_CSS_FILTERS = [ 'compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.datauri.CssDataUriFilter', ] # 5KB limit COMPRESS_DATA_URI_MAX_SIZE = 5 * 1024 # Explicitly enabled so it works in DEBUG mode as well COMPRESS_ENABLED = True However, I'm still seeing non-data URLs in generated CSS for images (and there are some images less than 5KB in size for sure). What am I missing? -
Manually running celery scheduled tasks within Django
In my Django settings file I have something that looks like this: CELERY_BEAT_SCHEDULE = { 'my_task': { 'task': 'tasks.my_task', 'schedule': crontab(hour=4, minute=0), 'kwargs': {'interval': 'hour', 'features': [], 'max_samples': 200, 'training_days': 90, 'force_update': False}, 'options': {'queue': 'my_queue'}, }, } What I would like to do is to be able to manually have this task asynchronously start. One way I know of to do this is: task = settings.CELERY_BEAT_SCHEDULE['my_task'] tasks.my_task.apply_async(kwargs=task['kwargs'], queue=task['options']['queue']) while this works it is a bit clunky for my tastes and I am looking for a better way. Is there a way to find celery's interpretation of the scheduled tasks defined in CELERY_BEAT_SCHEDULE and manually running them from there? The closest I have found so far is inspect().registered_tasks() from celery.task.control but that seems to be more about the workers than the scheduled tasks.