Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Include a ColorField in a form django
I'm trying to add a colorField using; https://djangosnippets.org/snippets/1261/ I added these to my models.py, class ColorField(models.CharField): def __init__(self, *args, **kwargs): kwargs['max_length'] = 10 super(ColorField, self).__init__(*args, **kwargs) def formfield(self, **kwargs): kwargs['widget'] = ColorPickerWidget return super(ColorField, self).formfield(**kwargs) Now in my forms.py, I am trying to use formField method, ( I 'am using a forms.Form form not a FormModel ) but doing: star_color = ColorField.formfield(ColorField) I keep getting errors: unbound method formfield() must be called with ColorField instance as first argument (got type instance instea) ?? -
Apps Registry error Django 1.8
Python version : 2.7.10 Django version : 1.8 Environment : Virtual environment Problem: Whenever i tried to run ./manage.py runserver or shell I get this error "The translation infrastructure cannot be initialized before the " django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time." Based on some responses on some related posts, I have also checked my wsgi file and it has the updated way of referencing the wsgi application. Here's how my wsgi file looks: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "instant_reports.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Any help/guidance on resolving this ? -
Django calling another model's upload_to inside a model
Let's say we have two models, A and B. Model A has an upload_to path and inside it, I also want to save a field from model B on the same path. Here's what I want to do: def random_path(instance, filename): #creating random path each time it's called class A(models.Model): imageA = models.ImageField(upload_to=random_path) # Randomly generated path def create_documentfiles(self): imageB = # Image saveImageB = DocumentImage(imagefile=imageB) saveImageB.imagefile.upload_to = # Should be same path as imageA saveImageB.save() class B(models.Model): imagefile = models.ImageField() I could define upload_to=random_path in B model, but it would give me a different path. So, I want the upload_to for model B be defined in model A. Not sure if it is even possible. Django docs don't mention anything similar to what I'm asking. -
Tango with Django : URLconf defined in tango_with_django_project.urls. Page not found
Started learning Django a few days ago, came across this book "Tango with django" and started following it. But I am stuck here..might be a silly error with the pattern matching.. The following error is shown : Error image /urls.py from django.conf.urls import url from django.contrib import admin from django.conf.urls import url,include from rango import views from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^rango/', include('rango.urls')), ] rango/urls.py from django.conf.urls import url from rango import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^about/', views.about, name='about'), url(r'^add_category/$', views.add_category, name='add_category'), url(r'^category/(?P<category_name_slug>[\w\-]+)/', views.show_category, name='show_category'), url(r'^category/(?P<category_name_slug>[\w\-]+)/add_page/', views.add_page, name='add_page'), ] views.py from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from rango.models import Category from rango.models import Page from rango.forms import CategoryForm from django.shortcuts import render def show_category(request, category_name_slug): context_dict = {} try: category = Category.objects.get(slug=category_name_slug) pages = Page.objects.filter(category=category) context_dict['pages'] = pages context_dict['category'] = category except Category.DoesNotExist: context_dict['category'] = None context_dict['pages'] = None return render(request, 'rango/category.html', context_dict) models.py from django.db import models from django.template.defaultfilters import slugify class Category(models.Model): name = models.CharField(max_length=128, unique=True) views = models.IntegerField(default=0) likes = models.IntegerField(default=0) slug = models.SlugField(unique=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Category, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'Categories' def __unicode__(self): return self.name def … -
Using RewriteRule in httpd.conf with Django (Apache + WSGI)
I'm running Django from an Apache server with mod_wsgi. I set up an auto-versioning template tag so that certain static resources are renamed using their file modification date, so that cached versions of the resource are not still used when the file is updated. The template tag does the following: Original Element: <script src="static/js/script.js"></script> Modified Element: <script src="/static/js/script.1498114658.js"></script> The modified element is what appears in the rendered template. Now, I need the server to detect paths like this, and redirect them to the actual resource (in this example, the actual resource is located at static/js/script.js). In my Apache's httpd.conf, I added the following directives: RewriteEngine on RewriteRule ^/static/(.*?)\.[0-9]+\.(css|js|jpe?g|gif|png) /static/$1\.$2 [L] But this does not seem to work. myhost.com/static/js/script.1498114658.js returns a 404 error, but myhost.com/static/js/script.js does not. Any ideas why this might be the case? I tried following the instructions from here. Thanks in advance! -
Django: calling objects from db returns <Queryset [...]>
I'm trying to get a very simple blogging application up, with all of the posts in my db displayed at once. However, my four posts are presented on the page as <QuerySet [<Post: Test content>, <Post: Second test post>, <Post: Third time's the charm>, <Post: Here is a post.>]> I'm also unable to pass any second variables to the html template like I would flask: testvar doesn't show up at all, even though it is in the html template. Are these problems related? How can I get multiple variables on the page, and how can I make the posts look like regular text? views.py: 1 from django.shortcuts import render 2 from django.http import HttpResponse 3 4 from .models import Post 5 6 def post(request ): 7 testvar = "TEST VARIABLE PLZ IGNORE" 8 post_list = Post.objects.order_by('id') 9 10 return render(request, 'posts/main.html', 11 {'post': post_list}, {'testvar': testvar}, 12 ) models.py: 1 from django.db import models 2 3 class Post(models.Model): 4 content = models.CharField(max_length = 200) 5 6 def __str__(self): 7 return self.content main.html: 1 <head> 2 <h1>{{ post }}</h1> 3 4 </head> 5 6 <body> 7 {{ testvar }} 8 {% for i in post_list %} 9 <li>i</li> 10 {% endfor … -
How to change key of lookup kwargs field in RetrieveAPIView in Django REST Framework?
Django REST Framework uses pk has the lookup field when using the RetrieveApiView and same has to be defined in the url kwargs . This makes the url look like : url(r'^(/foobar/(?P<pk>[\d]+)/$', FooBarFetch.as_view(), name="foo_bar") But I want to replace the pk in the url with something more descriptive like foo_bar_id. Changing the look_up_field doesn't work as it still has to use the pk to perform the lookup. Just kwrags key has to be changed in the url. -
Spaces around == operator in if tag
Django 1.11.2 This works: {% if n == "1" %} {{ n }} {% endif %} This doesn't: {% if n=="1" %} {{ n }} {% endif %} Traceback: Internal Server Error: /form/ Traceback (most recent call last): File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/template/smartif.py", line 175, in translate_token op = OPERATORS[token] KeyError: 'n=="1"' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/michael/workspace/simple_project/home/views.py", line 22, in get {"n": n}) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/template/loader.py", line 67, in render_to_string template = get_template(template_name, using=using) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/template/loader.py", line 21, in get_template return engine.get_template(template_name) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/template/backends/django.py", line 39, in get_template return Template(self.engine.get_template(template_name), self) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/template/engine.py", line 162, in get_template template, origin = self.find_template(template_name) File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/template/engine.py", line 136, in find_template name, template_dirs=dirs, skip=skip, File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/template/loaders/base.py", line 44, in get_template contents, origin, origin.template_name, self.engine, File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/template/base.py", line 191, in __init__ self.nodelist = self.compile_nodelist() File "/home/michael/workspace/venv/simple_project/lib/python3.5/site-packages/django/template/base.py", … -
Sorl thumbnail error: Requested setting DEFAULT_FILE_STORAGE, but settings are not configured
Getting this error from sorl.thumbnail version 12.3 when I try to import a model from shell. ImproperlyConfigured: Requested setting DEFAULT_FILE_STORAGE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. but the site runs okay from runserver. full error log In [1]: from gallery.models import Image --------------------------------------------------------------------------- ImproperlyConfigured Traceback (most recent call last) <ipython-input-1-ffea958a5ee6> in <module>() ----> 1 from gallery.models import Image /home/samuel/Documents/code/revamp/gallery/models.py in <module>() 2 3 from django.db import models ----> 4 from sorl.thumbnail import ImageField 5 from django.contrib.humanize.templatetags.humanize import intword 6 from django.template.defaultfilters import truncatechars /usr/local/lib/python2.7/dist-packages/sorl/thumbnail/__init__.py in <module>() ----> 1 from sorl.thumbnail.fields import ImageField 2 from sorl.thumbnail.shortcuts import get_thumbnail, delete 3 from sorl import __version__ 4 /usr/local/lib/python2.7/dist-packages/sorl/thumbnail/fields.py in <module>() 6 from django.utils.translation import ugettext_lazy as _ 7 ----> 8 from sorl.thumbnail import default 9 10 /usr/local/lib/python2.7/dist-packages/sorl/thumbnail/default.py in <module>() 1 from django.utils.functional import LazyObject 2 ----> 3 from sorl.thumbnail.conf import settings 4 from sorl.thumbnail.helpers import get_module_class 5 /usr/local/lib/python2.7/dist-packages/sorl/thumbnail/conf/__init__.py in <module>() 1 from django.conf import settings as user_settings 2 from django.utils.functional import LazyObject ----> 3 from sorl.thumbnail.conf import defaults 4 5 /usr/local/lib/python2.7/dist-packages/sorl/thumbnail/conf/defaults.py in <module>() 29 30 # Storage for the generated thumbnails ---> 31 THUMBNAIL_STORAGE = settings.DEFAULT_FILE_STORAGE 32 33 # Redis … -
Django user posts to be filtered from all posts and displayed in user profile
I am new to Python and Django and now developing a blog.I have this model that users can log in to the site and add their posts and all posts are displayed in home. At the same time I want the posts by the user to be displayed in user profile. My model for the blogpost is from django.db import models from django.utils import timezone class Blogpost(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title and the views.py is as under views.py from django.contrib.auth.decorators import login_required from django.shortcuts import render from blogpost.models import Blogpost def home(request): context = {} template = 'home.html' return render(request,template,context) def about(request): context = {} template = 'about.html' return render(request,template,context) @login_required(login_url='/accounts/login/') def userprofile(request): user = request.user context = {'user': user} user_posts=Blogpost.objects.filter(author=request.user).order_by('-published_date') template = 'profile.html' return render(request,template,context,{'user_posts':user_posts}) I am using this template for displaying the post from users returned by the query set. profile.html {% extends 'base.html' %} {% load staticfiles %} {% block blogprofile %} {{ user.username }} {{ user.email }} {% for Blogpost in user_posts %} <div class="post"> <div class="date"> <p>{{ Blogpost.published_date }}</p> <p>{{ Blogpost.author }}</p> </div> … -
Where do I set environment variables for Django?
everyone! Django 1.11 + PostgreSQL 9.6 + Gunicorn + Ubuntu 16.04 in AWS I want to set environment variables for sensitive info.(django secret key, DB password...) I studied many articles about setting ways. But when I tried os.environ['env_name'], .bashrc: Not working .bash_profile: Not working .profile: Not working /etc/environment: Not working Gunicorn script file.(systemd): I set them in gunicorn systemd script. It work very well. But because I want to use the environment variables in other program too, I set them among 1~5 configurations. I don't understand why 1~5 configurations didn't work. Is there scope or priority of setting environment variables? -
Django returns list index must be a number not a str
i have a python list [('failed',2L),('running',1L),('success',3L)]. and i can call it by indexes (ex.row[0] for 'failed,running,success' and row[1] for '2L,1L,3L'.and when i try to access it by values(ex.success) it returns index must be 'string'. if call by index is working why not call by value isn't? -
reverse/httpresponseredirect doesn't work in django
I'm making a multiple page form, where every single page will save data in different tables. Now, when I submit the form, my view should HttpResponseRedirect to a reversed url. But that's exactly what is not going on. The fact is that return HttpResponse(reverse('url') prints the right url, but HttpResponseRedirect doesnt redirect to the reversed url. This is the code: def get_form_naw(request, form_id, filterid, project_id): if request.method == 'POST': form = OpnameNawForm(request.POST) if form.is_valid(): form.save() form_id = int(form_id) + 1 url = reverse('opname:get_form', kwargs={'form_id': form_id, 'filterid': filterid, 'project_id': project_id}) return HttpResponseRedirect(url) else: form = OpnameNawForm() return render(request, 'opname/home.html', {'form': form}) urls.py url(r'^formulier/step/(?P<filterid>[^/?]+)/(?P<form_id>[^/?]+)/(?P<project_id>[^/?]+)/$', views.get_form, name='get_form'), -
Uploading large files with Django: How should one go about doing this?
I have to upload >= 20 GBs of data with Django. Should I break the file into chunks and then upload it with some kind of a checksum to maintain integrity or does Django implicitly does it? Will it be better if I use FTP instead of regular HTTP for such large files? -
How to resolve Django error "gaierror: [Errno -2] Name or service not known"?
I am creating a demo e-commerce website to learn Django with the help of a tutorial but unfortunately stuck at one place. I am now able to send the email form submit form. Its throwing an error like this: Internal Server Error: /contact/ Traceback (most recent call last): File "/home/jai/Desktop/tryten/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/jai/Desktop/tryten/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/jai/Desktop/tryten/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jai/Desktop/tryten/src/contact/views.py", line 18, in contact send_mail(subject, message,emailFrom, emailTo, fail_silently=True) File "/home/jai/Desktop/tryten/local/lib/python2.7/site-packages/django/core/mail/init.py", line 62, in send_mail return mail.send() File "/home/jai/Desktop/tryten/local/lib/python2.7/site-packages/django/core/mail/message.py", line 342, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/jai/Desktop/tryten/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 100, in send_messages new_conn_created = self.open() File "/home/jai/Desktop/tryten/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 58, in open self.connection = connection_class(self.host, self.port, **connection_params) File "/usr/lib/python2.7/smtplib.py", line 256, in init (code, msg) = self.connect(host, port) File "/usr/lib/python2.7/smtplib.py", line 316, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket return socket.create_connection((host, port), timeout) File "/usr/lib/python2.7/socket.py", line 553, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): gaierror: [Errno -2] Name or service not known I have tried all the things to rectify the error but its not working at all. Please help. its very frustrating. This is … -
How to show hits/views of individual posts on my post list? -Django
I am trying to display the number of views/hits of individual posts in my publication list page. I am using redis to store my hit/views. I have tried a few things, however, I am unable to get everything together. I am new to django(just one month old) and stuck with this problem for last 7-8 days. Could anybody please help me out? Any help would be much appreciated. Following are my two models.py: Comments: class CommentManager(models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter (content_type=content_type, object_id=obj_id) return qs class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='comment_by', default=1) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') content = models.TextField() created = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) objects = CommentManager() def __str__(self): return 'Comment by {} {}'.format(self.user.first_name, self.user.last_name) def count_comments(self): qs = Comment.objects.filter_by_object(self.object_id).count() return qs class Meta: ordering = ('created',) publications: class publication(models.Model): DOI = models.CharField(max_length=500, unique=True, blank=False, default='') title = models.CharField(max_length=500) slug = models.SlugField(unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) other_authors = models.CharField(max_length=2000, null=True) file = models.FileField(upload_to=upload_location, validators=[validate_file_type], null=True, blank=True) abstract = models.TextField(max_length=5000) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timeStamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("publication:post_detail", kwargs={"slug": self.slug}) class Meta: ordering = ["-timeStamp", "-updated"] @property … -
Django - create unique key that contains other models field
I'm trying to create 'unique_together' meta for a model, but instead of two fields from the current model, one of them is a field of other model (which is a foreign key in the current model): I want the 'Item' model to have unique_together that contains both its 'identifier' field and the Spec's container_id. a Spec is foreign key in 'Item'. Tried something like this, but I get "Unresolved reference spec..." class Spec(BaseModel): title = models.CharField(max_length=200) identifier = models.IntegerField(unique=True) container = models.ForeignKey(Container, related_name='specs') class Item(SubmittalsBaseModel, BaseModel, DirtyFieldsMixin): title = models.CharField(max_length=200) identifier = models.CharField(max_length=200, unique=True) spec = models.ForeignKey(Spec, related_name='items') class Meta: container_id = spec.container unique_together = ('identifier', 'container_id') -
How to rename upload file from input text
Im a newbie to code so im quite bad at it.Im using Django for the framework. Currently this is my html code for the user input. <form action="upload/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset> Category of the device:<br> <input type="text" name="category" value="" required> <br> Model:<br> <input type="text" name="model" value="" required> <br> <input type="submit" value="Upload File" class="submit" name="submit" /> <input type="file" name="file"/> </fieldset> </form> How do i rename the file that the user uploaded to have the text they input to the back of their filename with "_". eg: filename = myfile category = camera model = XYZ123 The file should be renamed to "myfile_camera_XYZ123". Please help -
Android Volley Url with paramwters
I have written a code using a volley library (GET) and I have to fetch the data from the rest API in Django. Actually the problem is i am getting a user id while i login , i just saved that id through shared preferences and i have to pass the id in the url to get wallet details but i am getting error BasicNetwork.performRequest: Unexpected response code 403 public class Wallet extends AppCompatActivity { TextView all_tv1; Button credit_bt, debit_bt; SharedPreferences pref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); overridePendingTransition(R.anim.fadein, R.anim.fadeout); setContentView(R.layout.activity_wallet); pref=getApplication().getSharedPreferences("Options", MODE_PRIVATE); Integer Key_UserID=pref.getInt("UserId_Value", 0); // String a = Key_UserID.toString(); /Json Request/ String uri = "http://staging.exol.in/wallet/wallet/api/wallet-detail/+Key_UserID"; RequestQueue requestQueue = Volley.newRequestQueue(this); JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, uri, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Toast.makeText(getApplicationContext(),"stop",LENGTH_SHORT).show(); // String data = ""; try { for(int i=0; i< response.length(); i++) { JSONObject obj = response.getJSONObject(i); String tnx_id = obj.getString("tnx_id"); String transition_type = obj.getString("transition_type"); // String email = obj.getString("email"); // System.out.print("\nggtrgtg"+user+"\ngfg"+amount); Toast.makeText(getApplicationContext(),tnx_id + transition_type ,LENGTH_SHORT).show(); // data = "" + id + "" + name + "" + email + ""; //txtDisplay.setText(txtDisplay.getText()+"\n" + id + "" + name + "\n" + email + ""); // Adds the data string to … -
Bulk create with unique constraint -- ignore duplicates
Let's say there's a model with unique constraint: class A(models.Model): my_unique_value = models.CharField(unique=True) I want to bulk_create As, but some of the my_unique_value values I'm inserting are already in the db. I want them to be ignored (not inserted). What is the best, most efficient way to achieve that? I cannot insert them one by one, and catch Exceptions (it's too slow). I also cannot fetch all As to clean duplicates first. The underlying DB is postgres. -
HTML to PDF result in landscape in Django using xhtml2pdf library
I have converted my HTML code into PDf but the output which I got is not in Landscape view, half of the page is empty which doesn't looks good. How can I get the pdf which can cover full page or any other way to remove the blank space. utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None views.py from django.http import HttpResponse import datetime from django.template.loader import get_template from django.template import Context from admin.models.certificate_appreciation import Appreciation_Certificate from admin.views.utils import render_to_pdf # created in step 4 def get_pdf_view(request, id, *args, **kwargs): template = get_template('certificate_appreciation_pdf.html') appreciation_certificate = Appreciation_Certificate.objects.get(id=id) context = Context({ 'appreciation_certificate': appreciation_certificate, }) html = template.render(context) pdf = render_to_pdf('certificate_appreciation_pdf.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % ("12341231") content = "inline; filename='%s'" % (filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" % (filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") template.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <style> body { font-family: Arial; } @page { size: … -
Can I use global variables in myapp.views.py to store data of different users in a django web application?
I am trying to design a web application in django in which a user uploads an exel sheet, some calculation will be done and user can view the calculted results filtered by a set of radio buttons. The end results are temporary and can be deleted as soon as the user logs out. So I am using only two templates one for sign in and one for my main page where I can upload file and view results. I am saving the end results as a dictionary of dictionaries as a global variable in myapp.views.py. Do I need to use a database for my requirement ? Also when multiple users sign in , I am thinking of saving the data as a global dictionary where key is username and value is end results for that user. Is this method correct? Is there any better way to fulfill my requirement ? When does the global variables in myapp.views.py will ceases to exist ? Sorry for the long explanation -
Django dictionary from env settings issue or django_rq issue?
I'm facing a strange behavior when trying to create Django_rq queues configuration dynamically from an environment variable. my env var is : CUSTOM_QUEUES=default:q1:q2 into my settings.py I have: from getenv import env # Cache CACHES_DEFAULT = "redis://127.0.0.1:6379/1" CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": env("CACHE_URL", CACHES_DEFAULT), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, 'TIMEOUT': 3600 }, } RQ_QUEUES_REDIS = {'USE_REDIS_CACHE': 'default'} RQ_QUEUES = {k:RQ_QUEUES_REDIS for k in env('CUSTOM_QUEUES', "default").split(':')} I'm expecting the denerated RQ_QUEUES dict to be like this one which is working : RQ_QUEUES = { 'default': { 'USE_REDIS_CACHE': 'default', }, 'q1': { 'USE_REDIS_CACHE': 'default', }, 'q2': { 'USE_REDIS_CACHE': 'default', }, } even though the configuration seems to run well and I can see the queues from django_rq web page, my workers cannot connect and actually throw this error as like there's no queue key in redis Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/work/virtualenv/runaway_dev/lib/python3.6/site-packages/django/core/management/init.py", line 350, in execute_from_command_line utility.execute() File "/home/work/virtualenv/runaway_dev/lib/python3.6/site-packages/django/core/management/init.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/work/virtualenv/runaway_dev/lib/python3.6/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/work/virtualenv/runaway_dev/lib/python3.6/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/work/virtualenv/runaway_dev/lib/python3.6/site-packages/django_rq/management/commands/rqworker.py", line 79, in handle queues = get_queues(*args) File "/home/work/virtualenv/runaway_dev/lib/python3.6/site-packages/django_rq/queues.py", line 166, in get_queues queue_params = QUEUES[queue_names[0]] KeyError: 'default' … -
Getting inherited class fields django
I am creating a custom user and profile model for my django application. I have created a user model and another profile model with OneToOneField to user model. I want to get profile model field values in template but only i can get object of user model in views from currently logged in user. How can I get profile model field values in the template ? models.py class UserSignup(models.Model): email = models.CharField(unique=True, max_length=254) name = models.CharField(max_length=100) password = models.CharField(max_length=1000) created_date = datetime.now() def __str__(self): return self.email class UserProfile(models.Model): user = models.OneToOneField(UserSignup, on_delete=models.CASCADE) full_name = models.CharField(max_length=200, null=True) #photo = models.ImageField(upload_to="/user/image/", blank=True) birth_date = models.DateField(null=True) books_wrote = models.TextField(null=True) journal_wrote = models.TextField(null=True) address = models.TextField(max_length=2000, null=True) @receiver(post_save, sender=UserSignup) def update_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) views.py def user_profile(request): op = UserSignup.objects.get(id=request.session['uid']) #here i want object of profile so i can access fields of profile in template return render(request, 'editor_profile.html', {'op': op}) template <div class="panel-heading"> <h3 class="panel-title">{{ op.name }}</h3> </div> <div class=" col-md-9 col-lg-9 "> <table class="table table-user-information"> <tbody> <tr> <td>Full Name:</td> <td>{{ op.full_name }}</td> </tr> <tr> <td>Company:</td> <td>{{ op.cmpny_name }}</td> </tr> <tr> <td>Website:</td> <td>{{ op.cmpny_website }}</td> </tr> <tr> <tr> <tr> <td>Experience:</td> <td>{{ op.experience }}</td> </tr> <tr> <td>Company Address</td> <td>{{ op.cmpny_address }}</td> </tr> … -
Django form with fields based on queryset
I'm trying to create a django form and I want one field for each Region (a class) I've the following form: class ShippingForm (forms.Form): def __init__(self, *args, **kwargs): super(ShippingForm, self).__init__(*args, **kwargs) from models import Region regions = Region.objects.all() for r in regions: self.fields['region_%d' % r.id] = forms.IntegerField(attrs={'class' : 'form-control'}) I based the above on this answer I have 4 Region records created but when I display this form in a template it is blank. What am I missing?