Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model does not declare a specific app_label
I have been trying to figure this out for quite a while now, and none of the answers I've found seem to work. I am getting an error that claims that I have not declared an app_label or put my app in INSTALLED_APPS. I definitely do have it in INSTALLED_APPS. I have put it to the top of my apps as well. I am not sure what else could be the problem. Originally, all these models worked when I had them inside users.models. I decided that there was way too much overlap between some things I need to do, and wanted to split out users that are resources, so I copied them over to resources.models. That is when all this nonsense happened. I thought I might have some circular dependencies, but I have been using string model references, so I don't think that is the problem, but I could be wrong. Does anyone have any ideas? Traceback: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fea802968c8> Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks … -
Moving from one app to another through urls = Django
I have a django project with two apps which are users and groups. I want to switch between both of them though an html redirect link in one of the templates. WHen the user clicks on the link, I want him to go from the users home page to the groups home page. For some reason, when I click the groups page, it does not redirect me to it. I stay on the users home page that just refreshes. I was wondering why this is happening. I know it hast something to do with the urls that I have an how they are setup but I am not sure exxactly where this issue is happening. I will attach all of the information below: app.urls file: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('users.urls')), url(r'^groups/', include('groups.urls')), ] Here is the users url file: urlpatterns = [ url(r'^$', views.user_home, name='home'), url(r'^login/$', views.user_login, name='login'), url(r'^logout/$', views.user_logout, name='logout'), url(r'^signup/$', views.user_signup, name='signup'), url(r'^profile/$', views.profile, name='profile'), url(r'^personal/$', views.verify_personal, name='personal'), url(r'^business/$', views.verify_business, name='business'), url(r'^test/$', method.test, name='test'), url(r'^search/$', views.search_user, name="searched"), url(r'^(?P<username>[\w+]+)/$', views.user_profile, name='user_profile'), url(r'^(?P<username>[\w+]+)/request/$', views.send_request, name='send_request'), url(r'^(?P<username>[\w+]+)/accept/$', views.accept_request, name='accept_request'), url(r'^(?P<username>[\w+]+)/decline/$', views.decline_request, name='decline_request'), ] here is the groups urls file: urlpatterns = [ url(r'^$', views.groups_home, name='groups'), ] here is the … -
Django Digitalocean Server won't update
I am working with DigitalOcean to run my django server for a client of mine but it appears as though my server has gotten 'stuck'. I was using the basic python library to send emails through django for testing purposes. Once I removed the code to send emails (because I was done with testing), my server refused to update. I've restarted gunicorn, nginx, and have done a full-on power cycle with digital ocean to no avail. What should I do? I can't find much online about how to resolve this issue, and I'm pulling my hair out on this one. Any ideas? -
How does render() determine url to use when rendering template
Have experimented with the view function below. It matches and renders fine. But have not been able to figure out via experiment/search how the url is determined that is used when the template is rendered. The matching/incoming url is "rec/play/new/". render() seems to use this same url when it renders e.g. "rec/play/new/" Is that always the case? How does determine to use this url. I thought via request, but even when the request is blanked out, it has no impact: return render(None, 'play/edit.html', {'form': RecForm()}) Still renders with url "rec/play/new/". How is it doing that? def rec_new(request): #matching url is "rec/play/new/" if request.method == "POST": form = RecForm(request.POST) if form.is_valid(): model = form.save(commit=False) model.save() return redirect('detail', pk=model.pk) else: return render(request, 'play/edit.html', {'form': RecForm()}) -
django query many to many returning only the id
model: class Planta(models.Model): created_at = models.DateTimeField(null=True, auto_now_add=True) updated_at = models.DateTimeField(null=True, auto_now=True) title = models.CharField(max_length=255, help_text="Digite o nome Cientifico", verbose_name="Nome Ciêntifico") descricao = models.TextField(null=True, blank=True, help_text="Digite uma breve descrição", verbose_name="Descrição") regioes = models.ManyToManyField(Regiao, verbose_name="Regiões em que é encontrada") def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.title class Regiao(models.Model): title = models.CharField(max_length=255, help_text="Digite uma região", verbose_name="Região da Planta") class Meta: verbose_name = 'Região' verbose_name_plural = 'Regiões' def __str__(self): """ String for representing the Model object (in Admin site etc.) """ return self.title my query is in this format: plantas = Planta.objects.prefetch_related( Prefetch( 'regioes', queryset=Regiao.objects.all() ) ) but still not working, planta.regioes still give me NONE the only thing that works is: plantas = Planta.objects.prefetch_related( Prefetch( 'regioes', queryset=Regiao.objects.all(), 'to_attr'='all_regioes' ) ) but now i should use attr planta.all_regioes and not planta.regioes anymore, how can i force it to load the regioes model inside the planta.regioes field, is that possible? the front receive in this way: [{'descricao': '', 'status': 0, 'sintomas': [15], 'modo_preparo': '', 'regioes': [10], 'title_cientifico': 'Nasturtium officinalis', 'partesdaplanta': [9], 'title_popular': 'Agrião', 'id': 5, 'imagem': }] look regioes:[10] and the others many to many too.. i'm looking for: regioes: [{ 'title': 'the region name' }] -
django using provider url patch
I am developing a django site that ,on my development environment, is accessed by the url localhost:8000. The url is automatically redirect to the url localhost:8000/accounts/login and, after login, to localhost:8000/iform/list. After deployed on my webserver, the app now is called icontrol, so, on the configuration panel of my provider, I set it to respond to the url www.mydomain.com/icontrol. When using the same files for development and deploy, after the login, instead redirect to www.mydomain.com/icontrol/iform/list, for example, its trying to redirecting to to www.mydomain.com/iform/list. How to make it work correctly on both environments? -
Passing an object into a Formset to filter the choices of a Choicefield
Goal I am trying to filter the Choices for a ChoiceField in forms within a Formset. Background The models I'm trying to create contain 3 fields: class TransactionChain(TimeStampedModel): new_sell_transaction = models.ForeignKey(Transaction, related_name="new") old_bought_transaction = models.ForeignKey(Transaction, related_name="old") num_sold = models.IntegerField() The user creates a new transaction, then is redirected to this formset view so the user can create a new TransactionChain & associate the new_sell_transaction to old_bought_transaction and the num_sold. I want to be able to filter the choices for the old_bought_transaction field. To filter the choices, I am trying to pass the created Transaction (new_sell_transaction) into the formset to then change the query for the old_bought_transaction. How I'm doing it now I'm using django-extra-views for a ModelFormSetView class TransactionChainView(LoginRequiredMixin, SetHeadlineMixin, ModelFormSetView): model = TransactionChain template_name = "transactions/transactionchain_form.html" headline = "Transaction Chain" transaction_status = "sell" class_url = 'transactions' fields = ('old_bought_transaction', 'num_sold',) extra = 3 initial = '' def get_object(self): return Transaction.objects.get( user=self.request.user, identifier=self.kwargs['identifier'] ) The url for this view includes an identifier to query the new Transaction. Question How do I pass that transaction into the formset, corresponding forms, and ultimately the old_bought_transaction to filter the choices like: self.fields['old_bought_transaction'].queryset = Transaction.objects.filter( user=transaction.user, color=transaction.color, ).exclude(identifier=transaction.identifier) -
Redirect to URL in Django
I use Django 1.11.3. I've created handlers.py file to use a custom method after Save button is pressed on some model. from django.db.models.signals import post_save from django.dispatch import receiver from curation.models import Article from django.http import HttpResponse @receiver(post_save, sender=Article) def send_to_data(sender, instance, **kwargs): if instance.state == '1': return HttpResponse('http://127.0.0.1:8000/admin/web/info/add/?info_id=' + str(instance.id), status=302) But the redirect doesn't work. I want to redirect user who pressed "Save" button to the new address. instance.state is 1, I checked it. If I print anything else it works, except for the redirect. I also tried with Django redirect and HttpResponseRedirect but I had the same problem. What am I missing? -
Create a django model for a table imported externally
I am new to django, so please excuse if I am totally wrong. I have a django installation in which some tables are manually imported from outside source. There is one table with large number of fields. In my current django I need to interact with only few of its fields. Can I create a django model for that table with just the fields I need and will it work? Will it mess up migrations completely? How is such a situation usually handled in django? -
run migrations in parallel django?
The current project has around 620 django models, which takes around 1 hour to migrate. . (uses only 12.x% of 8 core intel skylake with 1.2gigs of 30gigs ram on gcloud while migration) this metrics is combined for pg and python 2 (cpython). I assume that only a single core is used while migrating. [celery processes uses 100% CPU + 50% of ram. ] each migration is like, class Migration(migrations.Migration): initial = True dependencies = [ ('dist', '0001_initial'), ] operations = [ migrations.CreateModel( name='model name', fields=[ ... ... 60 fields ... ... ], options={ 'abstract': False, }, ), ] they are identical but with some minor changes to fields. Is there any way to migrate this database faster? can I run migrations on parallel? since migrations after 30 (internal apps and dists) are not related to each other, can I run these migrations in parallel? thank you -
Stop abstract django.test TestCase class from running test also
I am creating Django unit tests, and have some very similar models with repeated functionality. There are some differences however, so I created an abstract BaseTestCase class that other TestCase classes inherit from. It seems to be working fine except for the fact that when the TestCases that inherit from the BaseTestCase class are done running their tests, Django will still try to run the BaseTestCase classes tests as well. Shouldn't Django not want to run the tests on the abstract BaseTestCase? Is there some type of configuration I'm missing to ensure this doesn't happen? Test Case Layout class BaseTestCase(BaseTestCase): api = "" def test_obj_list(self): response = self.client.get(self.api) self.assertTrue(response.status_code == 200) def test_obj_create(self): pass def test_obj_retrieve(self): pass def test_obj_update(self): pass def test_obj_delete(self): pass class Meta: abstract = True class ChildTestCaseOne(BaseTestCase): api = "/api/v0.1/path_one/" class ChildTestCaseTwo(BaseTestCase): api = "/api/v0.1/path_two/" class ChildTestCaseThree(BaseTestCase): api = "/api/v0.1/path_three/" class ChildTestCaseFour(BaseTestCase): api = "/api/v0.1/path_four/" class ChildTestCaseFive(BaseTestCase): api = "/api/v0.1/path_five/" This should run 25 Tests, five tests for five test cases, but it runs 30. After it runs the 5 tests for each child class, it runs the 5 tests for the base test case as well. -
Error on "pip install -U channels" command using for otree (Running setup.py bdist_wheel for twisted ... error)
For a project using otree (http://otree.readthedocs.io/) I ran into some troubles trying to install Channels in order to make use of real-time functionalities. Because of the long output I tried to figure out the most important parts: For full output see: https://jsfiddle.net/L4ccmr2k/1/ Red marked output & considered relvant from my side: 1. Building wheels for collected packages: twisted Running setup.py bdist_wheel for twisted ... error 2. creating build/temp.macosx-10.6-intel-3.6 creating build/temp.macosx-10.6-intel-3.6/src creating build/temp.macosx-10.6-intel-3.6/src/twisted creating build/temp.macosx-10.6-intel-3.6/src/twisted/test /usr/bin/clang -fno-strict-aliasing -Wsign-compare -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -I/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c src/twisted/test/raiser.c -o build/temp.macosx-10.6-intel-3.6/src/twisted/test/raiser.o xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun error: command '/usr/bin/clang' failed with exit status 1 ---------------------------------------- Failed building wheel for twisted Running setup.py clean for twisted Failed to build twisted Installing collected packages: twisted, daphne, channels Running setup.py install for twisted ... error Complete output from command /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/private/var/folders/6_/30pgp_bj17j3krgq_kt0py440000gn/T/pip-build-v4kcayoj/twisted/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/6_/30pgp_bj17j3krgq_kt0py440000gn/T/pip-vpnlc5lo-record/install-record.txt --single-version-externally-managed --compile: 3. creating build/temp.macosx-10.6-intel-3.6 creating build/temp.macosx-10.6-intel-3.6/src creating build/temp.macosx-10.6-intel-3.6/src/twisted creating build/temp.macosx-10.6-intel-3.6/src/twisted/test /usr/bin/clang -fno-strict-aliasing -Wsign-compare -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -I/Library/Frameworks/Python.framework/Versions/3.6/include/python3.6m -c src/twisted/test/raiser.c -o build/temp.macosx-10.6-intel-3.6/src/twisted/test/raiser.o xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing … -
Log in user without giving access to admin interface
Working on a project that is powered by Django. Problem is I can't seem to find the way how to authenticate user without giving him access to the admin interface at the same time. I've read through numerous articles and tutorials about how Django handles authenticating visitors of the website and they all seem to go through creating user in admin and build a separate view for visitors to see where they're presented with login form to fill out. They don't seem to address the problem what if the user finds out that the website is built in Django, types "/admin hits enter and then just types in his/her credentials and vuala random visitor is in admin interface which isn't good at all ? -
form_invalid() missing 1 required positional argument: 'form'
Hi how are I having a problem with my django user authentication since I am using AbstractBaseUser Model from Apps.grupo.models import Grupo from Apps.empresa_area.models import Empresa_area from Apps.archivos.models import Archivos from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, Group, ) class UserManager(BaseUserManager): def create_user(self, email, password=None, is_staff=False, is_admin=False): if not email: raise ValueError("Usuuario tiene email") if not password: raise ValueError("usuario debe tener contraseña") user_obj = self.model( email =self.normalize_email(email) ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True, ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=200, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) celular = models.CharField(max_length=20) saludo = models.CharField(max_length=10) grupo = models.ForeignKey(Grupo, null=True, blank=True, on_delete=models.CASCADE) archivo = models.ForeignKey(Archivos, null=True, blank=True, on_delete=models.CASCADE) fec_creacion = models.DateTimeField(auto_now=False, auto_now_add=False) empresa_area_id = models.ForeignKey(Empresa_area, null=True, blank=True, on_delete=models.CASCADE) cargo = models.ManyToManyField(Group) USERNAME_FIELD = 'email' REQUIRED_FILES = [] objects = UserManager() class Meta: verbose_name = ('user') verbose_name_plural = ('users') def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): … -
Can't send email with Django celery
I am try to send email in my django project using Celery and RabbitMQ. Here is my project on GitHub https://github.com/Loctarogar/Django-by-Example. In my tasks.py file typed admin@myshop.com but i tried change it to my real google mail and that have no effects. Every time I have this Error: [2017-11-20 20:09:36,747: ERROR/ForkPoolWorker-4] Task orders.tasks.order_created[a8fe13ed-08dc-4971-82ff-f184e197ab8d] raised unexpected: ConnectionRefusedError(111, 'Connection refused') Traceback (most recent call last): File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/app/trace.py", line 374, in trace_task R = retval = fun(*args, **kwargs) File "/home/morilon/dj/shop/lib/python3.5/site-packages/celery/app/trace.py", line 629, in __protected_call__ return self.run(*args, **kwargs) File "/home/morilon/dj/shop/myshop/orders/tasks.py", line 14, in order_created mail_sent = send_mail(subject, message, 'admin@myshop.com', [order.email]) File "/home/morilon/dj/shop/lib/python3.5/site-packages/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/home/morilon/dj/shop/lib/python3.5/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/morilon/dj/shop/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 104, in send_messages new_conn_created = self.open() File "/home/morilon/dj/shop/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 64, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.5/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.5/smtplib.py", line 335, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.5/smtplib.py", line 306, in _get_socket self.source_address) File "/usr/lib/python3.5/socket.py", line 711, in create_connection raise err File "/usr/lib/python3.5/socket.py", line 702, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused -
Why am I getting this Django TypeError?
I am getting the following error: TypeError at /admin/KSUvity/activity/add/ coercing to Unicode: need string or buffer, User found models.py: class Activity(models.Model): type = models.CharField(max_length=50, default="") title = models.CharField(max_length=200, default="") description = models.CharField(max_length=500) owner = models.ForeignKey(User, related_name="owner") college = models.CharField(max_length=200) location = models.CharField(max_length=200) room = models.CharField(max_length=200) startDate = models.DateTimeField(null=True, blank=True) endDate = models.DateTimeField(null=True, blank=True) attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True) volunteer = models.ManyToManyField(Volunteer, related_name="volunteers",null=True, blank=True) created_time = models.DateTimeField(editable=False, auto_now= True) modified_time = models.DateTimeField(null=True, blank=True) def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.id: self.created = timezone.now() self.modified = timezone.now() return super(Activity, self).save(*args, **kwargs) class Attendee(models.Model): student = models.ForeignKey(User, related_name="attendee") In forms.py: class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ('type', 'title', 'description', 'owner', 'college', 'location', 'room', 'startDate', 'endDate', 'attendee', 'volunteer', ) From the admin page, I used to get an activity form and add activities. But I suddenly started to get this error. What might the problem be? -
Taking Attendance in Django Python
I am trying to mark attendance. But I am not able to get the code. My submit should send the input to database for each student. Any suggestion for doing this in better way is welcome. My models.py is as follows It has Employee, Mentor and Student and below is the model where values can be changed. class ClassName(models.Model): class_name = models.CharField(max_length=20) class_date=models.DateField(blank=True, null=True) Mentor= models.ForeignKey(Mentor, related_name='class_mentor') student = models.ManyToManyField(Student, related_name='class_student') attendance = models.BooleanField(default=True) def __str__(self): return str(self.class_name) Views.py : This is just to display the markattendance page. I am not able to figure out how to get the value and Post the value to database. Right now, I am fetching Students value from the Students table. I think I should be creating Classname Form and and display students. I was getting Internal server error. def markattendance(request): students = Student.objects.all() return render(request, 'home/markattendance.html', {'students': students}) markattendance.html : On clicking submit, the attendance should be marked.enter image description here {% extends 'home/index.html' %} {% block content %} <div class="container-fluid"> <div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Name</th> <th>Class</th> <th>Attendance</th> </tr> </thead> <tbody> {% for students in students %} {% ifequal students.Men_name|stringformat:"s" user.username %} <tr> <td>{{ … -
Typerror: __init__() got an unexpected keyword argument 'initial' error. When trying to use class-based views and crispy forms
This issue has been bugging me for days and I couldn't find an answer anywhere, I even suspect it`s actually a bug, but as I'm a django beginner who has just started to play around with class-based views I figured I might be doing something wrong. So, I created a simple UpdateView with LoginRequiredMixin to update my model and it works well, but if I try to customize the forms.py to use crispy forms I get and error. Here`s my code: models.py class Profile(TimeStampedModel): LANGUAGES = ( ('pt_BR', 'Português(Brasil)'), ('en_US', 'English(USA)'), ) user = models.OneToOneField('auth.User') language = models.CharField(max_length=255, choices=LANGUAGES, default=LANGUAGES[0][0]) def get_absolute_url(self): return reverse('edit-profile') forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('language',) labels = { 'language': 'Idioma', } views.py class ProfileUpdateView(LoginRequiredMixin, UpdateView): form_class = ProfileForm template_name = 'accounts/profile.html' def get_object(self, queryset=None): return self.request.user.profile So far so good, everything works if I generate a {{ form.as_p }} in my template. Now if I begin to customize my ProfileForm class in forms.py by inserting: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('language',) labels = { 'language': 'Idioma', } def __init__(self): super().__init__() # self.helper = FormHelper() # ... continue crispy form setup... Even before I instantiate any object … -
Django _set.all filter not working in template
I'm trying to filter a list of objects in my database but I can't get it to work on the template using _set.all. The strange thing is it's something I've done in two other places in my project but I cant see why it isnt working this time. view.py: class GolfMonthlyView(generic.ListView): template_name="monthly_view/golf-monthly-view.html" context_object_name='golf_monthly_view' queryset = GolfMonthlyView.objects.all() def get_context_data(self, **kwargs): context = super(GolfMonthlyView, self).get_context_data(**kwargs) context['golftour'] = golf_models.Tour.objects.all() context['golftournament'] = golf_models.Tournament.objects.all() models: class Tour(models.Model): name = models.CharField(max_length=100) class Tournament(models.Model): tour = models.ForeignKey('Tour', on_delete=models.CASCADE) name = models.CharField(max_length=100) template html: {% for info in golf_monthly_view %} {% for competition in golftour %} {% for golftournament in golftour.golftournament_set.all %} <ul> <li>{{golftournament.name}}</li> </ul> {% endfor %} {% endfor %} {% endfor %} The good news out of all this is in trying to work out my problem its forced me to use the Django Shell for the first time properly. So I know the relationship is there and functional, it just isnt displaying in the template. -
add a placeholder in these fields django
I'm really confused how to use placeholders. I'm using model that has a couple of fields of data and I want to have a place holder telling he user what to enter. So placeholder sounds like a good way to put this info into the text field. I'm using Crispy forms and fields come from the model. Here is my forms.py just don't know how to incorporate placeholders here if its even here where I need to do it. from django import forms from .models import MRReg class SignUpForm(forms.ModelForm): class Meta: model = MRReg fields = ['SiteID','HeliumValue'] def clean_HeliumValue(self): HeliumValue = self.cleaned_data.get('HeliumValue') #HeliumValue_base, provider = HeliumValue.split("@") #domain, extension = provider.split('.') #if not extension == "edu": #raise forms.ValidationError("Please use a valid .edu address") return HeliumValue #print (self.cleaned_data) def clean_SiteID(self): SiteID = self.cleaned_data.get('SiteID') raise forms.ValidationError("Please enter a valid SiteID") return SiteID -
Eliminate duplicity of serialized json data row in django
I am passing a json serialized data to an ajax request on my application after doing some queries on my django app. How can I eliminate duplicity of my data in the serialized data bellow "data_prod"? I would like to have in the dataset exclusive and unique rows. Thanks in advance. Views.py def product_table(request): width = request.GET['width'] length = request.GET['length'] prod_filter = Product.objects.filter(length=length,width=width).defer('volume') data_prod =serializers.serialize('json', prod_filter, fields=('width','length','Name','Model')) return JsonResponse({'data_prod':data_prod}) -
issue rendering Django Choice field from model on template
I'm trying to follow the example in the Django documentation to include a choice field to my form. I've created the following choice model: class Ref_AccessDescription(models.Model): FACILITY = '7' MARKET = '6' DIVISION = '5' GROUP = '4' CORPORATE = '3' DEVELOPER = '1' access_level_CHOICES = ( (FACILITY, 'Facility'), (MARKET, 'Market'), (DIVISION, 'Division'), (GROUP, 'Group'), (CORPORATE, 'Corporate'), (DEVELOPER, 'Developer'), ) access_level = models.CharField( max_length=1, choices=access_level_CHOICES, default=FACILITY, ) def is_corporate(self): return self.access_level in (self.CORPORATE) def is_developer(self): return self.access_level in (self.DEVELOPER) Then I create the following form pulling all objects: class AccessLevelForm(forms.Form): accesslevel = forms.ModelChoiceField(Ref_AccessDescription.objects.all()) I create the view to use the form passing my arguments: form = AccessLevelForm() errors = form.errors or None # form not submitted or it has errors args = {'retreivecheckbox': reportlist,'form': form,'errors': errors} return render(request,'accounts/requestaccess.html', args) When I try to render the form in a template, it doesn't populate it with my choice field. <label for="accesslevel">Access Level</label> <select class="form-control" id="accesslevel"> <option>{{ form.accesslevel }} </option> I've also tried to just use{{ form }}and nothing gets populated -
Getting session info from subdomains to the parent domain [Django]
I have a Django app that is hosted in a example.com. Users create groups/team, and each team gets a unique subdomain. Ex: team1.example.com Users log into their team from the team's subdomain. User A who is in team1 will log in from team1.example.com/login/. I have set it up this way so that two users logging in from the same browser for different teams (user A in team1.example.com and user B in team2.example.com), can maintain two separate sessions. Now the parent domain is www.example.com, and when user visits the parent domain, i want to be able to show the active sessions of all logged in users. Something like: Active sessions: Team 1 (team1.example.com) Team 2 (team2.example.com) I am using Django All-auth for authentication. NOTE: I am aware of the method making COOKIE_DOMAIN_NAME=".example.com" and having shared sessions across sub domains. I want to be able to maintain separate sessions for each sub domain. -
How to pass a pk from template in url to use in view "Django"?
I'm getting this error: "ValueError at /5 invalid literal for int() with base 10: '' " I think that I'm passing a string and trying to use it as an int. How do I pass the int I want correctly? This is the code I have, in the html template: <form method="GET" action="{% url 'register' activity.pk %}"> {% csrf_token %} <button type="submit" class="btn btn-primary" id="Register">Register </button> </form> In urls.py: url(r'^(?P<pk>)', authentication_views.registerAttende, name='register'), In views.py: def registerAttende(request,pk): act = Activity.objects.get(pk=pk) //This is the line that is causing the error act.save() attend = act.attendee.create(student=request.user.id) return render(request, 'dashboard.html') I'm getting that the value of of the variable pk is: u'' https://i.stack.imgur.com/uSw24.png How do I fix this? What am I doing wrong? -
Django Rest Framework custom ListSerializer only returning dictionary keys, not values
I am using a custom ListSerializer to reformat a JSON response and it generates the proper format when I log from inside the serializer, but when it is returned to the ViewSet, the response becomes a list of the dictionary keys rather than including the entire dictionary with both keys and values. I have made a simplified example of the problem with hard-coded JSON to illustrate what I believe to be the crux of the issue. views.py class ElementViewSet(viewsets.ViewSet): ... @detail_route(methods=['get']) def elements(self, request, pk=None): elements = ElementFilterSet(params) serializer = serializers.ElementSerializer(elements, many=True) return Response(serializer.data) serializers.py class ElementListSerializer(serializers.ListSerializer): def to_representation(self, obj): result = {"home": {"label_color": "#123456","label_text": "young"},"speak": { "label_color": "","label_text": "Hello"}} return result class ElementSerializer(serializers.ModelSerializer): class Meta: model = Element list_serializer_class = ElementListSerializer def to_representation(self, obj): result = super(ElementSerializer, self).to_representation(obj) return result The response I get is a list of dictionary keys: [ "speak", "home" ] rather than what I want, which is the entire dictionary (in this case, simply the hard-coded JSON result): { "home": { "label_color": "#123456", "label_text": "young" }, "speak": { "label_color": "", "label_text": "Hello" } } I am new to customizing serializers and using list_serializer_class; I likely simply don't understand how they work, but this behavior does …