Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Forms custom error message in views
This is my view: if request.method == 'POST': form = TeacherRegister(request.POST) #Gets school object from email domain. email = form['email'].value().split('@')[1] try: school = School.objects.get(email_domain = email) except ObjectDoesNotExist: #add custom error message here if form.is_valid(): user, Teacher = form.save() Teacher.school = school Teacher.save() user.groups.add(Group.objects.get(name='Teacher')) #user.is_active to stop users logging in without confirming their emails user.is_active = False user.save() #Sends confirmation link. send_confirmation_email(request, user) args = {'email': user.email, 'link': user.Teacher.school.email_website} return render(request, 'email/token_sent.html', args) else: args = {'form': form,} return render(request, 'users/teachers.html', args) These lines are what I am trying to work with: email = form['email'].value().split('@')[1] try: school = School.objects.get(email_domain = email) except ObjectDoesNotExist: #add custom error message here This is the HTML I have for the email field: <div class="required field" > {{ form.email.label }} {{ form.email }} {{ form.email.help_text }} <!-- <label>Email</label> <input placeholder="Email" type="email" name="email" autofocus="" required="" id="id_email"> --> </div> How can I get it to say, if no school object is returned, something along the lines of 'School not found, check your email'? Thanks -
Django - string primary key - get_absolute_url() result in no reverse match
I want to replace the default numeric primary_key with a string. This model was working fine with id, now I recreated it with prg and it fail in retrieving data URL. class Mymodel(models.Model): #id = models.AutoField(primary_key=True) prg = models.TextField(primary_key=True, unique=True) def get_absolute_url(self): # return reverse('label_app.views.label_detail', args=(self.pk,)) return reverse('label_detail', kwargs={'prg': self.prg}) lib/python3.5/site-packages/django/urls/resolvers.py in _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs) 495 "a valid view function or pattern name." % {'view': lookup_view_s} 496 ) --> 497 raise NoReverseMatch(msg) 498 499 NoReverseMatch: Reverse for 'model_detail' not found. 'model_detail' is not a valid view function or pattern this is the prg format: 'Number/number/number' from werkzeug I see: django.urls.exceptions.NoReverseMatch django.urls.exceptions.NoReverseMatch: Reverse for 'Model_detail' with arguments '('180036/10/1',)' not found. 1 pattern(s) tried: ['(?P[\w]+)/modeldetail/$'] what am I doing wrong? Thanks, BR -
django-rest-framework browsable API doesn't show login link
I am currently following the django-rest-api tutorial. In my urls.py, I created the urlpatterns like this: urlpatterns = format_suffix_patterns([ ... url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), ]) Now when i call any restricted endpoint in my browser, like 127.0.0.1/rest/api/foobar, I get the Browsable API with a 403 Forbidden, which is totally fine. But there is no login link in the top right corner. Why is that? What am I doing wrong? -
Django 1.11 best to approach to "quarter" logic for multiple purposes
I have a Survey app that includes a Survey model and a Response model. class Survey(models.Model): name = models.CharField(max_length=400) is_published = models.BooleanField() class Response(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) survey = models.ForeignKey(Survey, related_name="responses") I also have an admin view for displaying all users, and displaying the latest response a user has submitted class UserAdmin(admin.ModelAdmin): list_display = ('username', 'latest_response') def latest_response(self, obj): return obj.response_set.latest('created') I only have one Survey which I will release for Response every quarter. Currently, the UserAdmin view's latest_response returns the name of the Survey (charField). What I would like to do is use the Response's created or updated (whichever is latest) and, in the UserAdmin, display this as "Q1 2018" for example. I know this can be achieved relatively easily through Django 2.0 using the Date Function extract, but how would I do this using Django 1.11? -
Djagno admin add custom filter
i'm using django 1.10 and i need to display data and create a filter based on a value from a different model(which has a foreign key referencing my model that is used on the admin template) These are my 2 models: This one is used to generate the template: class Job(models.Model): company = models.ForeignKey(Company) title = models.CharField(max_length=100, blank=False) description = models.TextField(blank=False, default='') store = models.CharField(max_length=100, blank=True, default='') phone_number = models.CharField(max_length=60, null=True, blank=True) This is the other one that holds a foreign key reference to my first one: class JobAdDuration(models.Model): job = models.ForeignKey(Job) ad_activated = models.DateTimeField(auto_now_add=True) ad_finished = models.DateTimeField(blank=True, null=True) Inside my template i have been able to display the(latest)start and end times def start_date(self,obj): if JobAdDuration.objects.filter(job=obj.id).exists(): tempad = JobAdDuration.objects.filter(job=obj).order_by("-id")[0] return tempad.ad_activated And then i just call this inside the list_display and that is working fine. However i have trouble setting a filter field using this criteria. If i just add it to my list_filter then i get an error that there is no such field inside my model which is true (since that one is in another table that has reference to my job table). So i was wondering what is the right approach to solve this? Do i need … -
Django - init object has no attribute 'kwargs'
I am trying to filter a forms foreign key like in this post set variable into queryset of forms.py from my generic view or url However I am getting the error 'AddSubnet' object has no attribute 'kwargs' when I remove def init function then the issues are resolved. so I know its definitely something to do with this function but I'm not sure what. full trace: Traceback: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view 62. self = cls(**initkwargs) File "/itapp/itapp/sites/views.py" in __init__ 1001. site_id = self.kwargs['site_id'] Exception Type: AttributeError at /sites/site/add_subnet/7 Exception Value: 'AddSubnet' object has no attribute 'kwargs' views.py: class AddSubnet(CreateView): model = SiteSubnets template_name = "sites/edit_subnet.html" fields = ['device_data', 'subnet', 'subnet_type', 'circuit', 'vlan_id', 'peer_desc'] exclude = ['site_data'] @method_decorator(user_passes_test(lambda u: u.has_perm('config.add_subnet'))) def dispatch(self, *args, **kwargs): self.site_id = self.kwargs['site_id'] self.site = get_object_or_404(SiteData, pk=self.site_id) return super(AddSubnet, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_detail_subnets", args = (self.kwargs['site_id'],)) def __init__(self, *args, **kwargs): #site_id = kwargs.pop('site_id') site_id = self.kwargs['site_id'] self.fields['circuit'].queryset = Circuits.objects.filter(site_data=site_id) def get_form_kwargs(self, *args, **kwargs): kwargs = super(AddSubnet, self).get_form_kwargs() if kwargs['instance'] … -
Accidentally created a file(s) in my remote server and can't get rid of it
. The file(s) I want to remove are ystemctl restart gunicorn. I must have accidentally created this whilst writing systemctl restart gunicorn. Any idea how I can remove these. I've already tried: rm ystemctl which returns No such file or directory rm ystemctl restart gunicorn returns the same error. -
Django file upload for different apps within a project ?
I am working on a project which have various apps like protocol, prediction etc. to perform some calculation "protocol" and "prediction" apps requires user input in the form of file upload. I have implemented the bellow schema which uploads file successfully into the "media" directory which is present at the base project directory. I want to implement file upload in this way so that It can upload file for respective app directory rather a common media directory. My code was like this: Views.py def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) print uploaded_file_url return render(request, 'protocol/submit_job.html', {}) return render(request, 'protocol/main_protocol.html') urls.py url(r'^protocol/$', views.simple_upload, name='simple_upload'), html <form method="post" enctype="multipart/form-data"> <div class="heading"> <h1> Machine Learning Modeling.. </h1> <h2> Upload CSV files .. </h2> </div> {% csrf_token %} <input class="input" type="file" name="myfile"> <button class="button" type="submit"> Upload file and submit job </button> </form> {% if uploaded_file_url %} <p class="text" >File uploaded successfully. </p> {% endif %} this schema work for me and upload all the file into media directory.. What changes should I make to upload file in app specific manner. for example: prediction/Input/uploaded_file_1.csv protocol/Input/uploaded_file_2.csv -
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?