Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changed img.src does not get updated
I am updating an image source in my views. As a non-png-image is converted to a png one in the process, the file name also changes (for example from a.jpeg to a.png). Updating with img.src = img.src + '?' + d.getTime(); does not work, because the image name (and ending) does not update and as the original image is deleted, there is no image to display under this name (browser still tries to call old a.jpeg, which does not exist anymore). Is this even something that can be managed with jQuery or do I need to do this with Django? -
Pull Django App from Heroku
I have built a web app using Django and I'm using Heroku to host it. There is a form where users can enter information and that information is stored in a database (db.SQLITE3). So everything is getting stored in the database which is on the server. Next time when I'm pushing my project after making some changes, the updated server database is getting replaced by my backdated local database which basically deletes the new information. So, I realized, I have to pull (Obviously) the server side code first before making the changes. I have tried heroku db:pull which gives an error db:pull is not a heroku command. ! Perhaps you meant pg:pull? So I tried heroku pg:pull DATABASE_URL db --app mywebapp which is giving an error heroku-cli: Pulling postgresql-reticulated-26036 ---> db 'createdb' is not recognized as an internal or external command, operable program or batch file. I'm really confused now, can someone please tell me how to pull the project from Heroku? Or maybe how I can get the updated database? Thanks! -
Django: How to properly display formsets as radio-button group
I am trying to make a form for writing problem and providing choices for the problem. Correct choice for the problem is indicated by the selected radio button. Whether a choice id correct choice for a problem is indicated by boolean field Choice.is_correct_choice. In my templates, I have the following: {% for form in choice_form %} <input type="radio" name="selected_choice_number" value="{{ forloop.counter }}"> {{ form.as_p }} {% endfor %} choice_form is the formset containing choice. And, in views.py, I have: form = request.POST selected_choice_number = int(form['selected_choice_number']) print(form["selected_choice_number"]) for counter, form in enumerate(choice_form, start=1): choice = form.save(commit=False) choice.problem = problem choice.is_choice_correct = (selected_choice_number == counter) print(choice.choice_text, choice.is_choice_correct) choice.save() choice_form formset is instance of formset of following form: class MCQChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text'] labels = { 'choice_text': "", } widgets = { "choice_text": forms.Textarea(), } This is working fine but It looks ugly to me, specially the code in templates. How can I improve the code so that radio button logic is code to Python (form/views) instead of templates? -
How can i create a link that takes a user to another users profile page in Django
how to create a link for user profile page . A link that will take a user to another user profile page when clicked. I am using django frame work, I do not have any clue on how to start building my view and the url for this .As i have found little or no information in regards to this online .Thank you .I will very much appreciate if you give me a hint on how to build my url and view to create this link . -
Getting all likes on User's all posts
this is my models.py class Subject(models.Model): title=models.CharField(max_length=150) slug=AutoSlugField(populate_from='title',unique=True) body=models.TextField(max_length=5000, blank=True, null=True) author=models.ForeignKey(User, related_name='posted_subjects') created=models.DateTimeField(default=timezone.now) active=models.BooleanField(default=True) points=models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='liked_subjects', blank=True) How can I get all points of the subjects posted by a particular user? I mean if a User "Mark" has posted 30 subjects, how can I get the sum of all points of those 30 subjects? -
Error: One or more models did not validate, Add a related_name argument to the definition
I'm gettings this error when running "manage.py validate" in my application. Error: One or more models did not validate: ipn.paypalipn: Accessor for field 'custom' clashes with related field 'Actor.paypalipn_set'. Add a related_name argument to the definition for 'custom'. dashboard.paypalipn: Accessor for field 'custom' clashes with related field 'Actor.paypalipn_set'. Add a related_name argument to the definition for 'custom'. Am i missing something in Actor.models? @csrf_exempt def show_me_the_money(sender, **kwargs): ipn_obj = sender actor_id = ipn_obj.custom if actor_id == "Upgrade all users!": User.objects.update(paid=True) if ipn_obj.payment_status == "Completed": from actors.models import Actor from commerce.models import Transaction actor = Actor.objects.get(id=actor_id) accountdetails = actor.account_set.latest('pk') signupbonus = 0 transaction = Transaction() transaction.actor = actor transaction.amount = ipn_obj.mc_gross transaction.currency = ipn_obj.mc_currency transaction.transaction_flag = 'paid' transaction.transaction_type = 'deposit' transaction.payment_method = 'Paypal' transaction.payment_reference = ipn_obj.txn_id transaction.payment_message = 'OK' transaction.transaction_date = timezone.now() transaction.UserIp = actor_ip() transaction.save() currentamount = accountdetails.balance accountdetails.balance = float(signupbonus) + float(currentamount) + float(ipn_obj.mc_gross) accountdetails.save() payment_was_successful.connect(show_me_the_money) -
Django Signal multiple Object creation
I have a signal what is send to a function x with a object. def x(obj): Element.objects.filter(id=obj.id)delete() if obj.is_active: Element.objects.create(**new_element(object)) If more then one user send this this signal with the same ID the function raise a IntegrityError in the creation step. I tried within a transaction but that didn't helped. What would be the best way to prevent this error and make sure the element object exists? -
django using the primary key that was created to insert data into another table
I have 2 table. Schedule and BookAppt. After creating the schedule, i want to use the scheduleId that was create to be insert as one of the field in BookAppt. However my method has this error. File "C:\Django project\AppImmuneMe2\customuser\views.py", line 62, in my_django_view schedule = data['save1.scheduleId'] KeyError: 'save1.scheduleId' May i know what is wrong ? # Create a schedule user = data['patientId'] userId = MyUser.objects.get(userId=user) save_attrs_schedule = { "userId": userId, "date": data["date"], "startTime": data["time"], "endTime": end_time, "status": data["status"], } save1 = Schedule.objects.create(**save_attrs_schedule) # Create a BookAppt with schedule that was just created as foreign key patient = data['patientId'] patientId = MyUser.objects.get(userId=patient) schedule = data['save1.scheduleId'] scheduleId = Schedule.objects.get(scheduleId=schedule) saveget_attrs_bookappt = { "patientId": patientId, "clinicId": data["clinicId"], "date": data["date"], "time": data["time"], "scheduleId": scheduleId, } save2 = BookAppt.objects.create(**saveget_attrs_bookappt) -
VirtualEnv ImportError: No module named MySQLdb
I am receiving the error: ImportError: No module named MySQLdb whenever I try to run my local dev server and it is driving me crazy. I have tried everything I could find online: pip install mysqldb pip install mysql pip install mysql-python pip install MySQL-python easy_install mysql-python easy_install MySQL-python pip install mysqlclient I am running out of options and can't figure out why I continue to receive this error. I am attempting to run my local dev server from using Google App Engine on a Mac system and I am using python version 2.7. I am also running: source env/bin/activate at the directory my project files are and am installing all dependencies there as well. My path looks like this: /usr/local/bin/python:/usr/local/mysql/bin:/usr/local/opt/node@6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Python.framework/Versions/2.7/bin Does anyone have further ideas I can attempt to resolve this issue? -
regular expression in django 2.0.1
re_path(r'^(<int:album_id>[0-9]+)/$', views.view_details, name='view_details') why I am getting errors, how to write this regular expression in django version 2.0.1 -
Django nested filtering
I have problem with nested filtering. I have couple models like this: class EventLog(models.Model): date = models.DatetimeField() class Discount(models.Model): date_from = models.DatetimeField() date_to = models.DatetimeField() person = models.ForeignKey('Person') discount = IntegerField() class Person(models.Model): name = models.TextField() class Event(models.Model): person = models.ForeignKey('Person') event_log = models.ForeignKey('EventLog') Discount cannot be overlapping. And now I need rows like this: person, event_log, discount But if discount dont exist in EventLog period of time discount should be 0. I did annotation to get discount with Case and When expressions, but it retrive all rows even if discount is not in EventLog date. Propobly I must join Discount table with filters but dont know how. -
Where do I set environment variables on my Django Digital Ocean server?
I'm running my Django project on my Ubuntu 16.04 Digital Ocean server running Gunicorn/Nginx. I have my whole project except my settings.py file so am looking do add that in now - however don't want to hardcode the SECRET_KEY - so am looking to define an environment variable like it says in the Django docs: SECRET_KEY = os.environ['SECRET_KEY']. Where do I define this variable? Is it in my gunicorn config file (/etc/systemd/system/gunicorn.service) -
while doing pip install mod_wsgi is failing
I am trying to put my django site on apache and i am following these tutorial enter link description here In doing these by these command set "MOD_WSGI_APACHE_ROOTDIR=C:\xampp\apache pip install mod_wsgi I am getting these error. wsgi_apache.obj : error LNK2001: unresolved external symbol __imp_apr_conv_utf8_to_ucs2 wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_shared_make wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_shared_copy wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_free wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_alloc wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_shared_destroy wsgi_buckets.obj : error LNK2001: unresolved external symbol __imp_apr_bucket_shared_split wsgi_interp.obj : error LNK2001: unresolved external symbol __imp_ap_show_mpm wsgi_interp.obj : error LNK2001: unresolved external symbol __imp_ap_get_server_description wsgi_interp.obj : error LNK2001: unresolved external symbol __imp_ap_get_server_built wsgi_metrics.obj : error LNK2001: unresolved external symbol __imp_ap_get_scoreboard_process wsgi_metrics.obj : error LNK2001: unresolved external symbol __imp_ap_get_scoreboard_worker_from_indexes wsgi_metrics.obj : error LNK2001: unresolved external symbol __imp_ap_exists_scoreboard_image wsgi_thread.obj : error LNK2001: unresolved external symbol __imp_apr_threadkey_private_get wsgi_thread.obj : error LNK2001: unresolved external symbol __imp_apr_threadkey_private_set build\lib.win-amd64-3.6\mod_wsgi\server\mod_wsgi.cp36-win_amd64.pyd : fatal error LNK1120: 101 unresolved externals error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1120 I had already tried other lot answers available on stackoverflow but nothing works.Every help will be appreciated -
My view block for creating an object doesn't work
def create_employee(request): if not request.user.is_authenticated(): return render(request, 'blazon/login.html') else: form = EmployeeForm(request.POST or None, request.FILES or None) if form.is_valid(): employee = form.save(commit=False) context = { 'employee': employee, 'form': form, } employee.save() return render(request, 'blazon/create_employee.html', context) return render(request, 'blazon/employees.html', {'employee': employee}) return render(request, 'blazon/create_employee.html', {"form": form,}) This is my view function for creating new employees in my project. Form gets rendered and when i hit submit the object is populated in database but it does not get redirected to employees.html page. i have tried return redirect('blazon:employees) instead of the render funtion above. how do i redirect to employees.html page? TIA -
How to return Multiple rows of data/objects using a filter in django
Please help me How can i return/query Multiple rows of Objects using a filter in django ex. campus = the_campus I have a field named campus in my table and i want to query all objects with the value given..... -
django get data from two tables using same model
I'm wishing to pull data from two tables having same structure. Currently i'm changing model._meta.db_table in views. The following code gives error in the last line LogEntry._meta.db_table = 'auditlog_logentry' logs_1 = [l.as_json() for l in LogEntry.objects.all().order_by('-id', 'object_repr')] LogEntry._meta.db_table = 'auditlog_logentry_1' logs_2 = [l.as_json() for l in LogEntry.objects.all().order_by('-id', 'object_repr')] the error is (1054, u"Unknown column 'auditlog_logentry.id' in 'field list'") the as_json method is as follows: def as_json(self): return dict( content_type=self.content_type, object_pk=self.object_pk, object_id=self.object_id, object_repr=self.object_repr, action=self.action, changes=self.changes_str, actor=self.actor.username, remote_addr=self.remote_addr, timestamp=self.timestamp, additional_data=self.additional_data ) Is it possible to change the db_table in views to fetch data from two tables. -
How to copy paste FileField?
This is how i upload file from form to FileField in the backend: the_file = request.FILES['newProfilePicture'] the_customer = Customer.objects.first() the_customer.profile_picture = the_file the_customer.save() But here is the problem, how do i get that filefield and then "copy paste" it to another object that has a different "upload_to" data? The Customer object: class Customer( models.Model ): profile_picture = models.FileField(upload_to='uploads/customer/%Y/%m/%d/') The Customer_Alternative object: class Customer_Alternative( models.Model ): profile_picture = models.FileField(upload_to='uploads/customer-alternative/%Y/%m/%d/') My current problem is that when i do the followings, it simply use the same picture instead of "copy-pasting" it to the new directory: old_customer = Customer.objects.all().first() new_customer_alternative = Customer_Alternative( profile_picture=old_customer.profile_picture, ) new_customer_alternative.save() So if i delete the FileField on that Customer object, it will also delete the data of the Customer_Alternative. Is there anyway to "copy paste" the data instead? -
Django + SSL + nginx + uwsgi + EC2
For the past couple of week's I've been trying to deploy a Django website that I made (using HTTPS everywhere) on an Redhat Amazon EC2 instance. I deployed the website using nginx and uwsgi but when I try entering the IP address of my EC2 instance I get a connection timed out. (My professor isn't going to use a hostname) Nginx will successfully redirect me to https, but anything I've tried so far has led me to this dreaded "Connection time out, too long to respond" screen. I've reads many tutorials online and threads on stackoverflow but have had no luck so far. Any help would be greatly appreciated. uWSGI 2.0.15 compiled with version 4.8.5 20160623 - I run the command (uwsgi --ini /etc/uwsgi/sites/uwsgi-django.ini) nginx 1.12.1 - I have it setup as a service (sudo service nginx start) Python 3.4 Django 2.0.1 My Amazon EC2 instance has port 80 and 443 open. My Nginx configuration is as follows: events { worker_connections 1024; } http { # nginx.conf # Redirects any requests on port 80 (http) to https: server { server_name 35.164.X.X; listen 80 default_server; rewrite ^ https://35.164.X.X$request_uri? permanent; access_log /spool/nginx-redirect.log; error_log /spool/nginx-redirect-error.log; } # django pass-thru via uWSGI, only from … -
Django: How to display formset as radio button group
I have my Form and Formset defined as below: class MCQChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ['choice_text', 'is_choice_correct'] labels = { 'choice_text': "", 'is_choice_correct': "" } widgets = { "choice_text": forms.Textarea(), # attrs={'rows': 2, 'cols': 15} # "is_choice_correct": # do something here } MCQSingleChoiceFormSet = formset_factory(MCQChoiceForm, min_num=4, max_num=4, extra=0) MCQSingleChoiceFormSet represents choices for a problem which can only have once correct choice. Choice.is_correct_choice field indicates if the given choice is correct. My Question: How can I display is_choice_correct field as a single radio button? True or False values saved in database will depend on whether the radio button is selected or not. How can I change my code so that only one of the radio buttons in the formset is selected? -
Allow user to edit a blog post live with Django
I'm making a blog feature on a website and I want to allow the User to edit the text of the post without taking them to a different view. Just like you can edit a post on Facebook, or on Stack. This is just the piece of code containing the form. {% if user.is_authenticated %} <button style="text-align:left;" class="content-editor"> <!-- line displays the text, I want to be able to make this editable on click --> <p class='body-font'>{{ post_detail.text|linebreaksbr }}</p> <!--the actual form that allows you edit, obviously it's just sitting there right now --> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </button> {% endif %} I'm not sure where to go from here, in my mind when the button is clicked, I should have some HTML that appears and replaces the HTML that was displaying just the text. The new editable text would be a model that is created by and passed from a view right? -
Django unittest throwing disabling autocommit
I'm trying to write Django 1.11 Selenium unittests using the LiveServerTestCase, but I'm getting the strange non-deterministic error: TransactionManagementError: Your database backend doesn't behave properly when autocommit is off. Turn it on before using 'atomic'. The traceback follows to the point in a test where I call a factory method, which I create using the DjangoModelFactory class in factory-boy like: class CompanyFactory(factory.DjangoModelFactory): name = factory.Faker('company') status = factory.LazyFunction(models.Status.objects.first) region = factory.SubFactory(RegionFactory) owner = factory.SubFactory(UserFactory) class Meta: model = models.Company and my test method looks like: class Tests(StaticLiveServerTestCase): def test_company(self): autocommit = transaction.get_autocommit() print('autocommit:', autocommit) self.assertEqual(autocommit, True) company = CompanyFactory() # This throws the exception # test stuff... The StaticLiveServerTestCase/LiveServerTestCase inherits the TransactionTestCase, so each test gets wrapped in an atomic context manager, which creates a transaction in auto-commit mode. When I first started getting this error, I added the print of the output for transaction.get_autocommit() to confirm where autocommit was being turned off...but to my amazement, it's not. The test confirms autocommit is correctly turned on...until the call to the factory method. So then I thought the factory class is somehow breaking the transaction. However, when I went to test just the test method that was failed...I found it passed … -
How to Bundle Polymer Elements in a Django App
I'm using Polymer 2.0 and Django 1.9 in my project. Currently my Polymer elements are loading extremely slow in my app. So I've decided to polymer-bundle my elements. I'm facing a problem with that right now whereas my elements don't have just 1 entry-point. I'm used to loading templates in my views with request like index.html or login.html etc. Those are my entry points. But polymer-build only allows 1 entry point e.g. index.html. I want to be able to bundle my polymer-elements but how do I do so if I have more than 1 entry-point? -
django ListView query_set code abbreviation
The codes are as models.py class Firm(models.Model): name = models.CharField(unique=True, max_length=50, verbose_name="Firma Adı") slug = models.SlugField(unique=True, editable=False, max_length=50) class Worksite(models.Model): firm = models.ForeignKey('Firm', verbose_name='Firma', related_name="worksites", on_delete=models.CASCADE) name = models.CharField(unique=True, max_length=50, verbose_name="Şantiye Adı") slug = models.SlugField(unique=True, editable=False, max_length=50) class Subcontractor(models.Model): worksite = models.ForeignKey('Worksite', on_delete=models.CASCADE) firm = models.ForeignKey('Firm', related_name="subcontractors", on_delete=models.CASCADE) Can the queryset code be written shorter? views.py class SubcontractorListView(ListView): template_name = 'firm/subcontractor_list.html' context_object_name = "firms" def get_queryset(self): ws = self.request.user.firm.worksites.values_list('id', flat=True) ss = Subcontractor.objects.values_list('firm_id', flat=True).filter(worksite_id__in=ws) return Firm.objects.filter(id__in=ss) Do you have different and short solutions? template {% for firm in firms %} <div class="btn btn-outline-secondary text-left button">{{ firm }} </div> {% endfor %} -
Why this django form not pass value back using initial argrument from view.py?
I have a form: class ConfigNotifyForm(forms.Form): sensor_name = forms.ChoiceField(widget=forms.Select(), label="Sensor", choices=[], required=True) value_min = forms.FloatField(label="Value Min", required=True) value_max = forms.FloatField(label="Value Max", required=True) def __init__(self, *args, **kwargs): super(ConfigNotifyForm, self).__init__(*args, **kwargs) # Get 'initial' argument if any initial_arguments = kwargs.get('initial', None) sensor_choices = '' if initial_arguments != None: #for choice in initial_arguments.get('src_choices'): sensor_choices = tuple(initial_arguments.get('src_choices')) self.fields['sensor_name'].choices = sensor_choices It's work ok with template. But when submit, sensor_name not in cleandata except value_min, and value_max. So, it not pass form.is_valid. But, if I code init like this: def __init__(self, *args, **kwargs): super(ConfigNotifyForm, self).__init__(*args, **kwargs) sensor_choices = ( ('', 'Select'), ('a0', 'Ndo'), ('a1', 'pH'), ('a2', 'DO')) self.fields['sensor_name'].choices = sensor_choices It's OK. Form is valid. I don't know why. Can anyone help me explain and resolve this issue ? Thanks -
type of object 'NewsletterUsuario' has no len()
i'm new using django as a framework, i got a problem when i try to save a newsletter on my custom control_panel, i can save the message but the web crash and showme a typeError telling me about a class model i made 'NewsletterUsuario' but just on de custom control_panel, in django admin mode it works normally, the problem start to happen after i eliminate some files from a app that i did not want to use and even i did a git reset to a working version still get this similar typeError, here is my models, views and traceback: models.py from django.db import models # Create your models here. class NewslettersUsuario(models.Model): email = models.EmailField() fecha_agregado = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class Newsletter(models.Model): EMAIL_STATUS_CHOICES = ( ('Draft', 'Draft'), ('Published', 'Published') ) subject = models.CharField(max_length =250) body = models.TextField() email = models.ManyToManyField(NewslettersUsuario) status = models.CharField(max_length=10, choices=EMAIL_STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.subject Views.py from django.conf import settings from django.contrib import messages from django.shortcuts import render from django.core.mail import send_mail, EmailMultiAlternatives from django.template.loader import get_template from .models import NewslettersUsuario, Newsletter from .forms import NewslettersUsuarioSignUpForm, NewsletterCreacionForm # Create your views here. def newsletter_signup(request): form = NewslettersUsuarioSignUpForm(request.POST or None) …