Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django [ create userS with specific permission ]
I'm developing an E-Learning Platform, however, there are a specific requirement. First the Admin Can create 2 type of Users [ Teacher - Student ] Admin: Only the Admin can Create a Course and HomeWorkS for a specific Course. Assign Teacher to a specific course and can only view it, no other Courses are accessible to him. Assign a Student to a specific Homework and\or course. Teacher: The Teacher can only See the Course [ it's been assigned to ] and The homeworkS and Can Ask Student to re-Do it. Student : Student - Can only see the homeWorks and submit it and re-Do it if the Teacher request it. I tried DRY principle but I couldn't solve the issue. Any help Is really appreciate it. Thank you -
getting dynamic loop values of input tag when a button is clicked
{% for key,value in a.items %} <tr> {% csrf_token%} <td>{{key}}</td> <td> <input type="hidden" value={{key }} name="software_selected"/> <button type="submit" class="btn btn-success btn-xs" data-toggle="tooltip" title="Accept" value="{{key}}" id="button3"><span class="glyphicon glyphicon-ok-sign"></span></button> </td> </tr> {% endfor %} ========= Ajax function: $(function() { jQuery(document).on('click', "#button3", function(){ var abc = []; $.each($("input[name='version_selected']:checked"), function(){ abc.push($(this).val()); }); var software_name=$("input[name='software_selected']").val(); alert(software_name) alert("My favourite sports are: " + abc.join(", ")); $("input[name='version_selected']:checkbox").prop('checked', false); //var abc = $("$button1").val(); event.preventDefault(); $.ajax({ type: 'POST', url: "{% url 'testing:test' %}", data: { 'abc[]': abc ,'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType : "json", success: function(data){ alert(data); }, error: function(xhr, status, e) { $("#error_text").html(data); } }); }); }); //I have a loop where i am having key values i need to fetch the key value dynamically on every button click on the ajax call.but as of now i am only able to fetch the first value var software_name=$("input[name='software_selected']").val();.Not getting all the values. Can anyone suggest some ways how to proceed? -
TypeError: create_superuser() missing 1 required positional argument: 'name'
i get the following error even after adding name to my create_superuser function in my models.py file from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager # Create your models here. class UserProfileManager(BaseUserManager): def create_user(self,email,name,password=None): if not email: raise ValueError("email is required") email=self.normalize_email(email) user=self.model(email=email,name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,password): """creates new super user with details """ user=self.create_user(email,name,password) user.is_superuser=True user.is_staff=True user.save(using=self._db) return user class UserProfiles(AbstractBaseUser,PermissionsMixin): email=models.EmailField(max_length=255,unique=True) name=models.CharField(max_length=255) is_active=models.BooleanField(default=True) is_staff=models.BooleanField(default=False) objects=UserProfileManager() USERNAME_FIELD='email' REQUIRED_FIELD=['name'] def get_fullname(self): return self.name def get_shortname(self): return self.name def __str__ (self): return self.email and i get the following kind of error when i tried to run python manage.py createsuperuser command TypeError: create_superuser() missing 1 required positional argument: 'name' i dont know where i my mistake is ? any kind of help is appreciated thanks in advance -
Python objects.all command not registering?
I am trying to make a for loop that prints out every user in my database to my website page... the only problem is that the attribute "objects" refuses to register and I do not understand the problem... def index(request): all_users = UserInfo.objects.all() context = {'all_users':index} for user in all_users: url = '/index/' + str(user.id) + '/' # html = '<a href="' + url + '">' + all_users + '</a><br>' return render(request, 'userData/allUsers.html', context) That is my code, and the error is "Unresolved attribute reference 'objects'". class UserInfo(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) name = "User:" + str(first_name) + " " + str(last_name) + "." SERVER_ROLE = ( ('creator', 'CREATOR'), ('admin', 'ADMIN'), ('moderator', 'MODERATOR'), ('normie', 'NORMIE'), ) role = models.CharField(max_length=10, choices=SERVER_ROLE, default='normie') This is the class that "UserInfo" relates to; if you need any more of my code I can add it to the question. -
Installing Django-channels error
I'm trying to develop a chat application in Django on mac OS. I've tried to install Django-Channels in virtualenv, with this commands: pip install channels pip install django-channels but this error occurred: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/4c/xy3rtg_165l0650j4tq7fvrh0000gn/T/pip-install-7anqvzhg/twisted/ Python version = 3.5.2, Django version = 1.11, pip is already up-tp-date -
How to implement an iterative algorithm using Django or Celery?
I want to implement an iterative algorithm as follows: repeat y = f(x) // client requests parameter x from server, then it computes y x = g(y) // parameter y is send to server for the computation until total time budget exhausted So it looks like we need a long running process p which is responsible for fetching parameter y and computing the function g to get parameter x. After that this process should be blocked until the client finish the computations. Then it starts the computation of next iteration. My question is can Django or Celery meets my demands above? And how? -
Select a valid choice ModelMultipleChoiceField error
I'm trying to make form that allows to user selecting employers by the checkbox list, depends on their team using ModelMultipleChoiseField. I can filter proper employers per team but when i select any of then i had error Select a valid choice. 3 is not one of the available choices. And i don't know what is wrong ;/ This is my form class : class TaskDictForm(forms.Form): team_id = 0 order = forms.IntegerField(min_value=0) name = forms.CharField(max_length=200) start = forms.DateTimeField() previous = forms.CharField(max_length=200) employers = forms.ModelMultipleChoiceField(queryset=None, widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): initial = kwargs.get('initial', {}) if hasattr(self, 'initial_values') and not kwargs.get('data'): for field_name, value in self.initial_values.items(): if not getattr(kwargs.get('instance', None), field_name, None): initial[field_name] = value kwargs.update({'initial': initial}) if hasattr(self, 'required_fields'): for field_name in self.required_fields: self.fields[field_name].required = True tmp = kwargs.pop('pk', None) self.team_id = tmp super(TaskDictForm, self).__init__(*args, **kwargs) self.fields['employers'].queryset = Employer.objects.filter(team=self.team_id) -
Not able to get the response from django rest api using requests.get() method
I have created a Django Rest Application and exposed one service (To get the User List) Now when I am trying to call thru curl request, I am able to get the User List. curl -v -XGET -i 'http://XXX.XX.XX9.XX1:8000/ebxxx/api/users/' But When I try to call it from another app using requests.get() method , I am getting 504 server error: I am trying : header = {"Content-type":"application/json"} response = requests.get("http://XXX.XX.XX9.XX1:8000/ebxxx/api/users/", headers=header) Error: "response , response<504>" -
Custom manager for related filter queries
According to the documentation https://docs.djangoproject.com/en/2.0/topics/db/managers/#django.db.models.Model._base_manager Base managers aren’t used when querying on related models. For example, if the Question model from the tutorial had a deleted field and a base manager that filters out instances with deleted=True, a queryset like Choice.objects.filter(question__name__startswith='What') would include choices related to deleted questions. But I need to use a Custom manager for querying on related models. I'm not filtering out any rows. Here is the actual requirement. When a query like Choice.objects.filter(question__name__startswith='What') is made, I need to modify it to Choice.objects.filter(question__alias__startswith='What') where 'name' and 'alias' are fields of the Question model. -
Django Use Many To Many with Through in Form
I have a data model where I am using a manual intermediate table for a m2m relationship. Building on the classical example from the django doc: from django.db import models INSTRUMENT_CHOICES = ( ('guitar', 'Guitar'), ('bass', 'Bass Guitar'), ('drum', 'Drum'), ('keyboard', 'Keyboard'), ) class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Leadership') def __str__(self): return self.name def get_leadership(): return self.leadership_set.first() class Leadership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) instrument = models.CharField('Playing Instrument', choices=INSTRUMENT_CHOICES, max_length=15, null=True, blank=False) class Meta: unique_together = ('person', 'group') When I create a new group I also want to specify who is going to be the leader, and for this relationship also specify which instrument he will play in that group. What really confuses me, given also the lack of documentation on this topic is how to handle this kind of relationship in forms. This is the form I came with: class InstrumentField(forms.ChoiceField): def __init__(self, *args, **kwargs): super().__init__(INSTRUMENT_CHOICES, *args, **kwargs) class GroupForm(forms.ModelForm): instrument = InstrumentField(required=False) class Meta: model = Group fields = ['name', 'members' 'instrument'] # This works but it's not correctly initalized in case of edit form def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance.pk … -
Django-celery with django2.0 in production with supervisor keeps sending tasks but completes none
These are the last 100 lines of my django celery log seems like no job is getting executed. [2018-06-26 10:42:57,286: INFO/Beat] Writing entries (1)... [2018-06-26 10:42:57,388: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:43:57,405: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:44:57,421: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:45:57,417: INFO/Beat] Writing entries (1)... [2018-06-26 10:45:57,448: INFO/Beat] DatabaseScheduler: Schedule changed. [2018-06-26 10:45:57,449: INFO/Beat] Writing entries (0)... [2018-06-26 10:45:57,642: INFO/Beat] DatabaseScheduler: Schedule changed. [2018-06-26 10:45:57,643: INFO/Beat] Writing entries (0)... [2018-06-26 10:46:56,207: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:47:56,223: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:48:56,238: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:49:01,319: INFO/Beat] Writing entries (1)... [2018-06-26 10:49:56,253: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:50:21,415: INFO/Beat] DatabaseScheduler: Schedule changed. [2018-06-26 10:50:21,416: INFO/Beat] Writing entries (1)... [2018-06-26 10:50:56,268: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:51:56,285: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:52:06,385: INFO/Beat] Writing entries (1)... [2018-06-26 10:52:56,300: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:53:56,317: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:54:56,334: INFO/Beat] Scheduler: Sending due task save_fullstory (get_articles.tasks.save_stories) [2018-06-26 10:55:11,445: INFO/Beat] Writing entries (1)... [2018-06-26 10:55:56,349: INFO/Beat] Scheduler: Sending due task save_fullstory … -
In Django, trying to encode .wav file using base64 encoding , but getting this error
audio_content = open("okay.wav").read() AUDIO_FILE = base64.b64encode(audio_content) screen shot of the error I am getting I am trying to encode .wav file using base64 encoding but getting this error any suggestion ?? -
How to access url kwargs in generic API views (ListCreateAPIView to be more specific) in django rest framework?
How to access url kwargs in generic API views (ListCreateAPIView to be more specific) in django rest framework, for example say I want to override the get_queryset() method inside a generic APIView class and I want it to use values as extracted from url kwargs, how would I do this? -
Django: validating hidden input
I am currently in need of some advice regarding best practices when it comes to validating hidden input. My situation requires me to connect some objects, and I have a form with some fields that provide information about how these should be connected. Though, I also need to know which objects to connect, and I thought best to do this using hidden input. There will be two hidden input fields, both providing pk's, integers. These will not be generated through by the form - I will write the HTML manually. Now, my idea for validating that no tampering is done to these hidden input fields is this: I will add two integer-fields to the form, two fields that will not be rendered at all, that share the names of the hidden input fields. Hopefully, this would mean that the hidden fields are validated just like all the other fields when run: form = my_form(request.POST) # request.POST containing hidden-fields as well form.is_valid(): Would this be a relatively safe way of checking that nothing else than integers are passed via the hidden input? Would this be as safe as normal form processing? Or am I missing something? -
Graphene-Python: automatic schema generation from Django model
I am trying to generate a Graphene schema from a Django model. I am trying to do this by iterating through the apps then the models and then adding the appropriate attributes to the generated schema. This is the code: registry = {} def register(target_class): registry[target_class.__name__] = target_class def c2u(name): # camelcase to underscores s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() class AutoSchemaMeta(type): def __new__(meta, clsname, superclasses, attributedict): new_class = type(clsname, superclasses, attributedict) for app_name in new_class.app_models.split(","): app_models = apps.get_app_config(app_name.strip()).get_models() for model in app_models: model_name = model.__class__.__name__ _node_class = type("{}Node".format(model_name), (DjangoObjectType,), {"Meta":{"model": model, "interfaces": (Node,), "filter_fields": []}}) register(_node_class) setattr(new_class, "all_{}s".format(c2u(model_name)), DjangoFilterConnectionField(_node_class)) setattr(new_class, "{}".format(c2u(model_name)), Node.Field(_node_class)) return new_class class Query(metaclass=AutoSchemaMeta): app_models = "app1,app2" When I run my application I get an exception: AssertionError: Found different types with the same name in the schema: ModelBaseNode, ModelBaseNode. What am I doing wrong here? -
Django send_mail socket.error 97
I'm using Django 1.7.7 and simple code to send mail: def sendEmailToAdmins(subject, msg): send_mail(subject, msg, settings.INFO_EMAIL, ADMIN_EMAILS, fail_silently=False) It was working good, but now I have this trouble: File "parser.py", line 1264, in <module> sendEmailToAdmins(subject, msg) File "/data/parser/immoscout/../../carbonimmo/front/utils.py", line 9, in sendEmailToAdmins ADMIN_EMAILS, fail_silently=False) File "/usr/local/lib/python2.7/dist-packages/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/usr/local/lib/python2.7/dist-packages/django/core/mail/message.py", line 286, in send return self.get_connection(fail_silently).send_messages([self]) File "/usr/local/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py", line 92, in send_messages new_conn_created = self.open() File "/usr/local/lib/python2.7/dist-packages/django/core/mail/backends/smtp.py", line 50, in open self.connection = connection_class(self.host, self.port, **connection_params) File "/usr/lib/python2.7/smtplib.py", line 251, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.7/smtplib.py", line 311, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python2.7/smtplib.py", line 286, in _get_socket return socket.create_connection((host, port), timeout) File "/usr/lib/python2.7/socket.py", line 571, in create_connection raise err socket.error: [Errno 97] Address family not supported by protocol PS. No changes to linux or Django settings didn't done. Email sends to @gmail.com -
I am trying to integrate filebased session in django
I am trying to integrate filebased session in django. I have followed all the provided details But session is not working. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/tmp/django_cache', } } I am getting below error Exception Type: OperationalError Exception Value: no such table: django_session -
Django - Changing Auth username to Autofield breaks the code
I've an application where I need to change username field to Autofield. Use-case - I'am building an application where when the users will be created, usernames should be like CustomerID(integers) in banking applications. There are 2 ways of doing it:- 1) Have an id (PK), the default implementation of it. Copy the id, of the object and assign it to the username column, to allow users to sign-in via the id. Trade-offs Two duplicate columns. How would I call create_user function as it requires username. 2) Allow login via the IDs, update AuthBackend and allow login via the IDs too. TradeOff What will be the value of the username. Shall I keep it as email? Not sure, whether allowing login via the IDs is a good idea. Pheww, enough of discussion. Now comes the implementation(problematic) part.:- Here's my model. class User(AbstractUser): username = models.BigAutoField(primary_key=True) user_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) A model can't have more than one AutoField, as a result, username is PK. I migrations worked perfectly well. And the table was created. However, when I create a user using User.objects.create_user(email=email, password=password) #expecting the username to be auto-generated. It says username is mandatory. I checked Django code UserManager function create_user, … -
ip address hyperlink in Django
In my Django template I am having some problem to hyperlink. The link is a dynamically generated IP (not a file location). in views.py def basestations(request, host_id): 'ipaddr': basestation.mni_address some code return render_to_response('basestations.html', locals(), context_instance=RequestContext(request)) This variable holding the dynamically produced IP address from database and passes to front end in the variable name basestation.mni_address In Django template, I want the basestation should be hyperlinked with the basestation.mni_address <td><a href="{% url what should I write here? %}"><i class="icon-th-large"></i> {{ basestation.name }}</a></td> Any help is much appreciated. -
How to refresh the page when custom plugin is saved?
I have created a website using Django cms. When I save the custom plugin the template is not rendered. But it is rendered when I refresh the page. So, how to refresh the page while saving the django cms custom plugin or any other way to render the template when the plugin is saved. But the content is saved in the admin side. I am not able to see the content in the template. -
rollbar django suddenly not working. AttributeError: module 'lib' has no attribute 'X509_up_ref'
My rollbar suddenly does not work on my django python app. It was working previously until i merge something. it looks more like openssl issue? >>> import rollbar >>> rollbar.init('xxxxxx', 'production') >>> rollbar.report_message('Got an IOError in the main loop', 'warning') 'xxxx-xxx-xxx-xxx-xxx' >>> From cffi callback <function _verify_callback at 0x7f08351e8730>: Traceback (most recent call last): File "/home/deploy/railerdotcom/railerdotcomenv/lib/python3.5/site-packages/OpenSSL/SSL.py", line 313, in wrapper _lib.X509_up_ref(x509) AttributeError: module 'lib' has no attribute 'X509_up_ref' I am using: Django==1.11.7 Ubuntu version 16.04 -
Testing DataField to accept only data in past. Clean(), Django, AssertionError
I am trying to write the test to check if my DataField accepts only data in the past but It doesn't work properly. forms.py class BookForm(PermissionRequiredMixin, ModelForm): class Meta: model = Book fields = ['title', 'author', 'summary', 'tag', 'genre', 'language', 'book_format', 'read_date'] def clean_read_date(self): data = self.cleaned_data['read_date'] #Check date is not in future. if data > datetime.date.today(): raise ValidationError('Invalid date - book read date in future!') return data test._forms.py class BookFormTest(TestCase): def test_book_form_date_in_futuret(self): date = datetime.date.today() - datetime.timedelta(days=10) form_data = {'read_date': date} form = BookForm(data=form_data) self.assertTrue(form.is_valid()) Does anyone know why my clean_read_data doesn't work? I know that probably I can do that in different ways but I read that using clean() is the best way to check that DateField is in future or in the past. -
How to use django packages in your app?
i am making a car booking system. and beginner in web development its my first django project . i had covered poll app tutorial. i want to built a booking system . i want to use this package https://github.com/bitlabstudio/django-booking in my django application . i want to use this package features for my car booking . how do i attach and make it working with my app. Views.py class CarDetailView(DetailView): context_object_name = 'car_details' model = models.Car template_name = 'buggy_app/car_detail.html' class BookingView(FormView): template_name = 'buggy_app/booking.html' form_class = BookingForm models = Booking def form_valid(self, form): form.save() return super(BookingView, self).form_valid(form) success_url = reverse_lazy('index') def get_context_data(self, **kwargs): try: kwargs['car'] = Car.objects.get(id=self.request.GET.get('car', '')) except (Car.DoesNotExist, ValueError): kwargs['car'] = None return super(BookingView, self).get_context_data(**kwargs) def get_initial(self): initial = super(BookingView, self).get_initial() if 'car' in self.request.GET: try: initial['book_car'] = Car.objects.get(id=self.request.GET['car']) except (Car.DoesNotExist, ValueError): pass return initial Models.py class Booking(models.Model): booking_name = models.CharField(max_length=240, null=False) customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='book_customers' ) book_car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name='book_car') booking_start_date = models.DateTimeField(auto_now_add=True, blank=False) booking_end_date = models.DateTimeField(blank=True, null=True) rental_price = models.IntegerField(blank=False, null=False) times_pick = models.TimeField(blank=True) is_approved = models.BooleanField(default=False) def __str__(self): return self.booking_name def get_absolute_url(self): return reverse("buggy_app:detail",kwargs={'pk':self.pk}) -
Admin panel css not working with daphne
I am was making a django chat application, The application's admin panel worked fine when I was using it with django inbuilt server but when I started using daphne The admin panel's css was not loading (404 Not found). This only happened with dapne. I could although work around with collectstatic method of django. but I still could not understand why it was not working with daphne, and weather there was any other way rather than collect static. Thank you in advance :) -
AttributeError at /share/4 'str' object has no attribute 'get'
I am tring to sent email with django using gmail smtp server i write settings in setting.py.here is my other code but I am getting AttributeError at /share/4 'str' object has no attribute 'get' ? please help me to solve that error. **forms.py** from django import forms class EmailPostForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() to = forms.EmailField() comment = forms.CharField(widget=forms.Textarea, required=False) views.py def share_email(request, id): post = get_object_or_404(Post, id=id) sent = False if request.method == 'POST': form = EmailPostForm(data=request.method) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_uri(post.get_absolute_url()) subject = '{} ({}) recommend you reading "{}"'.format(cd['name'], cd['email'], post.title) message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comment']) send_mail(subject, message, 'admin@gmail.com', cd['to']) sent = True else: form = EmailPostForm() return render(request, 'blog/post/share_post.html', {'post': post, 'form': form, 'sent': sent}) url.py urlpatterns = [ path('share/<int:id>', views.share_email, name='share_post'), ] share_post.html {% extends 'blog/base.html' %} {% block title %} Share Post {% endblock %} {% block content %} {% if sent %} <h2>E-mail successfully sent</h2> <p>{{ post.title }} is successfully dent by email</p> {% else %} <h2>Share {{ post.title }} by email</h2> <form action="{% url 'blog:share_post' post.id %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send Email"> </form> {% endif %} …