Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django on Google App Engine: "Instance names cannot contain the ':' character."
I am following this tutorial to run a Django project on Google AppEngine. I have reached the steps to create a Cloud SQL instance. When I follow these steps I get the following error: $ gcloud sql instances describe django-polls-184415:us-west1:polls ERROR: (gcloud.sql.instances.describe) Instance names cannot contain the ':' character. If you meant to indicate the project for [polls], use only 'polls' for the argument, and either add '--project django-polls-184415:us-west1' to the command line or first run $ gcloud config set project django-polls-184415:us-west1 When I follow the instructions in the error message, I get $ gcloud config set project django-polls-184415:us-west1 Updated property [core/project]. $ gcloud sql instances describe polls ERROR: (gcloud.sql.instances.describe) HTTPError 403: The client is not authorized to make this request. What am I doing wrong? And more importantly how do I do it correctly? -
How do you make SQL return duplicates?
When running an SQL such as the following; SELECT * FROM items WHERE item_name IN ('fish', 'frog', 'fish') I get 1 frog, and 1 fish. This is expected and normal behaviour, as the WHERE clause no doubt evaluates against each row in the database individually. However, in my current application I need a full row returned for each item in the WHERE clause. The way I'm currently doing it is fetching the full contents of the IN statement, then running a second query fetching each of those objects. In python, I am then duplicating the rows as required. But if I could get sql to do it for me, it'll mean 1 less round trip to the database. Can you force a database to return a response per entry in an IN? Example data; items id | name | price 1 | frog | 4 2 | fish | 3 objects for users id | user_id | item_name 1 | 1 | fish 1 | 1 | frog 1 | 1 | fish I'm aware that item_name should be a foreign key to item instead - but for frustrating legacy reasons, this is not currently possible. An ideal solution would … -
Django upload model - user permissions
I am creating a file upload page which has a file upload model: models.py class Upload(models.Model): file = models.FileField(blank=True, null=True, validators=[validate_file_extension]) upload_date = models.DateTimeField(auto_now_add=True) class Meta: permissions = ( ('can_upload_x', 'Can Upload X'), ('can_upload_y', 'Can Upload Y'), ('can_upload_z', 'Can Upload Z'), ) forms.py class UploadFileForm(forms.ModelForm): class Meta: model = Upload fields = ['file'] html {% if perms.app.can_upload_x %} <form action="#" method="post" enctype="multipart/form-data"> <input type='hidden' name='action' value='x'> {% csrf_token %} {{form_x}} <input type="submit" value="Upload" id="weights_btn" name="weights_btn" class="btn btn-default btn-file"/> </form> {%endif%} #etc for X, Y, Z, .... So the end goal is for the users assigned to have certain permissions from the admin like 'can_upload_x' will only be able to see the form for X etc ( I make different forms save to different locations with handle_uploaded_file in the views). What am I doing wrong? does not seem to work. It did, however work when I had a model for each form but it is unfeasible for my project since I might have to have a whole lot of different forms. Thank you! -
redirect to view from another view NoReverseMatch error django
Helo everyone, I have two views but I can't redirect to view from another view. Before asking this question I tried some solutions from stackoverflow, but they they didn't bring any result. Please help. VIEWS.py def new_room(request): new_room = None while not new_room: with transaction.atomic(): label = haikunator.haikunate() if Room.objects.filter(label=label).exists(): continue new_room = Room.objects.create(label=label) return redirect('chat', label=label) def chat(request, label): room, created = Room.objects.get_or_create(label=label) messages = reversed(room.messages.order_by('-timestamp')[:50]) return render(request, "chat/room.html", { 'room': room, 'messages': messages, }) Thanks in advance! -
every url is redirected to gitlab page
I wanted to have gitlab CI and django in digital ocean. I created a droplet and configured the gitlab with the following settings external_url = "http:/lab.###.com/" # gitlab_rails['gitlab_email_from'] = "gitlab@example.com" # gitlab_rails['gitlab_support_email'] = "support@example.com" # gitlab_rails['smtp_enable'] = true # gitlab_rails['smtp_address'] = "smtp.server" # gitlab_rails['smtp_port'] = 465 # gitlab_rails['smtp_user_name'] = "smtp user" # gitlab_rails['smtp_password'] = "smtp password" # gitlab_rails['smtp_domain'] = "example.com" # gitlab_rails['smtp_authentication'] = "login" # gitlab_rails['smtp_enable_starttls_auto'] = true # gitlab_rails['smtp_openssl_verify_mode'] = 'peer' # nginx['redirect_http_to_https'] = false # nginx['ssl_certificate'] = "/etc/gitlab/ssl/gitlab.crt" # nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/gitlab.key" and here is my nginx settings server { listen 80; server_name 150.200.##.## abc.com www.abc.com; client_max_body_size 50M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/root/eatplus-django; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000/; proxy_redirect off; # proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 30; proxy_read_timeout 30; } } when i enter lab.##.com, I am redirected to gitlab which is expected but when entering ip address and www.###.com I am still redirected to gitlab page which is unexpected behavior. How do i resolve this? -
How to achieve left join without where clause in Django
House.objects.filter(owner__isnull=True) will produces following SQL: SELECT "app_House"."id", "app_House"."name" FROM "app_House" LEFT OUTER JOIN "app_Owner" ON ("app_House"."id" = "app_Owner"."house_id") WHERE "app_Owner"."id" IS NULL Is there a syntax available to force Django to omit the where clause? -
How to connect Django's built-in username and password fields to user-defined html input tags
I have used a pre-defined html template for my login form and I have tried to connect the django's standard/built-in username and password fields namely {{ form.username }} and {{ form.password }} to the input fields of the html template. It works fine, but it populates the fields with None in both of the username and password fields everytime a user is redirected to the login page. When using the {{ form.username }}and{{ form.password }}` template tags, they are populated with valid user credentials. Is this normal or I am missing something here? Here is the code that I have tried to use an input field instead of Django's built-in username and password field: <!-- username input field--> <div class="group"> <label for="{{ form.username.id_for_label }}" class="label">Username</label> <input id="{{ form.username.id_for_label }}" maxlength="100" name="{{ form.username.html_name }}" value="{{ form.username.value }}" type="text" class="input"> </div> <!-- password input field--> <div class="group"> <label for="{{ form.password.id_for_label }}" class="label">Password</label> <input id="{{ form.password.id_for_label }}" maxlength="100" name="{{ form.password.html_name }}" value="{{ form.password.value }}" type="password" class="input"> </div> -
Setting up a Webpack Configured Vuejs Admin with Django REST API Backend
I need help on how to plugin an existing Vuejs Project (e.g. an Admin Dashboard) to a Django Project with Rest API, I'm having some issues with the Webpack configuration. I went through this: https://ariera.github.io/2017/09/26/django-webpack-vue-js-setting-up-a-new-project-that-s-easy-to-develop-and-deploy-part-1.html But still need help in reusing the Vuejs Admin with the Django Project. -
Show Validation Errors -- TemplateView, FormView
I have a template with multiple forms, but i can not figure out how to show the validation errors. For simplification i show only one form and how i try to update 'hostname' of the model Protocol. As soon i always raise a validation error (just for testing) in forms.py with: def clean(self): raise forms.ValidationError("Validation Error Test") I get the message: AttributeError at /add_hostname/666666/ 'str' object has no attribute 'get' If i remove clean() the update works fine -- but i want to validate some things in there. I guess i can not use the line of code in views.py when the form is not valid? return reverse('protocol-detail', kwargs={'slug': self.kwargs['protocol_id']}) What is the right way to go? models.py class Protocol(models.Model): protocol_id = models.PositiveIntegerField(unique=True) hostname = models.CharField(max_length=12, blank=True) #... views.py class Protocol_Detail_View(TemplateView): template_name = 'app_name/template.html' def get(self, request, *args, **kwargs): comment_form = Comment_Form(self.request.GET or None) hostname_form = Hostname_Form(self.request.GET or None) task_form = Task_Form(self.request.GET or None) context = self.get_context_data(**kwargs) # protocol_id = self.kwargs['slug']) context['protocol'] = Protocol.objects.filter(protocol_id=self.kwargs['slug']).get() context['comment_form'] = comment_form context['hostname_form'] = hostname_form context['task_form'] = task_form return self.render_to_response(context) class Hostname_Form_View(FormView): form_class = Hostname_Form def post(self, request, *args, **kwargs): hostname_form = self.form_class(request.POST) if hostname_form.is_valid(): Protocol.objects.filter(protocol_id=self.kwargs['protocol_id']).update(hostname=request.POST['hostname']) return super(Hostname_Form_View, self).form_valid(hostname_form) else: return reverse('protocol-detail', kwargs={'slug': self.kwargs['protocol_id']}) def … -
How to update an instance in Django rest framework?
I have a question about how I can update an instance in django rest framework. So basically I want to update my user profile through an request but I cannot get current user Id. Is there a better way to get current user and update its information? This is not working because request.user is always anonymous. @api_view(['POST']) def update_profile(request): serializer = AccountSerializer(request.user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Thank you so much! -
Django REST API Multiple Records Same Category
There is a problem with Django Rest API , i have a 2 records in my creators table. first records have category "gaming" and the second record have category "Education" all is ok for now , but when i add Thirds record with Category "Education"(same category of first record ) then i got the error when i call all records of That Category(gaming). i want the multiple records of same category model.py class Creators(models.Model): title=models.CharField(max_length=200) link = models.CharField(max_length=200) subscriber = models.PositiveIntegerField() country = models.CharField(max_length=100) email = models.CharField(max_length=100) description = models.TextField(max_length=2000) category = models.CharField(max_length=100) socialLinks = models.TextField(max_length=2000) class Meta: ordering = ('title',) serializer.py class CreatorsSerializer(serializers.ModelSerializer): class Meta: model = Creators fields = "__all__" views.py class CreatorsList(APIView): def get(self,request,category): creator = Creators.objects.get(category=category) serializer = CreatorsSerializer(creator) return Response(serializer.data) def post(self): pass urls.py url(r'^creators/(?P<category>\w+)/$', views.CreatorsList.as_view()), when i run example.com/creators/Gaming/ then it gives me perfect output(for now i just have 2 records) { "id": 1, "title": "channel1", "link": "https://www.youtube.com/channel/UCJbPGzawDH1njbqV-D5HqKw", "subscriber": 2000, "country": "PK", "email": "ishaq@gmail.com", "description": "ddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnknd", "category": "Gaming", "socialLinks": "ddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnknd" } but when i added third records of same category (Gaming) the error shows MultipleObjectsReturned at /creators/Education/ get() returned more than one Creators -- it returned 2! i also added many=True in views.py but … -
How to load data from Django to a variable for a D3 graph
I want to know how can I update a variable from a backend in Django, and update the graph I am building on the front end with D3, without refreshing the page, that is, do the update dynamically. I managed to update the graph, but each time I change the parameters in the form in the front-end, it renders the whole page, I just want to update the data and refresh the graph in D3. Here is my view: def growth(request): parsedData = [] if request.method == 'POST': year_input = request.POST.get('years') year_input_int = int(year_input) growth_data = requests.get('https://www.ons.gov.uk/economy/grossdomesticproductgdp/timeseries/ihyp/qna/data') # jsonList = [] # jsonList.append(json.loads(growth_data.content)) parsed_json = json.loads(growth_data.content) growthData = {} data_input = 'years' for data in parsed_json[data_input][year_input_int:]: growthData['date'] = data['date'] growthData['value'] = data['value'] growthData['year'] = data['year'] parsedData.append(growthData.copy()) return render(request, 'dashboard/growth.html', { 'growth_json': json.dumps(parsedData) }) Here is my form HTML, <form method= "post" action="/indicators/growth/"> {% csrf_token %} <br> <select type="text" name="years"> <option value="60">2009</option> <option value="61">2010</option> <option value="62">2011</option> </select> <br> <button type="botton">Get Data</button> </form> -
Send error mail to admin in Django
I am trying to send a mail to ADMIN when any exception is occurred in django. So i tried but not able to find the solution. I don't have a clear idea about how to send a error mail to admin Any help would be appreciated. Views.py def emit(self, record): try: request = record.request subject = '%s (%s IP): %s' % ( record.levelname, ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS else 'EXTERNAL'), record.getMessage() ) filter = get_exception_reporter_filter(request) request_repr = '\n{}'.format(force_text(filter.get_request_repr(request))) except Exception: subject = '%s: %s' % ( record.levelname, record.getMessage() ) request = None request_repr = "unavailable" subject = self.format_subject(subject) if record.exc_info: exc_info = record.exc_info else: exc_info = (None, record.getMessage(), None) message = "%s\n\nRequest repr(): %s" % (self.format(record), request_repr) reporter = ExceptionReporter(request, is_email=True, *exc_info) html_message = reporter.get_traceback_html() if self.include_html else None self.send_mail(subject, message, fail_silently=True, html_message=html_message) def send_mail(self, subject, message, *args, **kwargs): mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs) def connection(self): return get_connection(backend=self.email_backend, fail_silently=True) def format_subject(self, subject): """ Escape CR and LF characters, and limit length. RFC 2822's hard limit is 998 characters per line. So, minus "Subject: " the actual subject must be no longer than 989 characters. """ formatted_subject = subject.replace('\n', '\\n').replace('\r', '\\r') return formatted_subject[:989] def test_view(request): try: raise Exception except Exception as … -
Global variable in a module, read after multiple write
I am working on Django project, but this question could also be Python generic. Answers that utilize specific Django feature can also be accepted. I am trying to define a global variable as a dict in a module. I require that this variable can be accessed by other module. The difficult part is, this global variable can be set/update multiple times by indefinitely many other modules at build time. After all the set/update, the variable can be read to set some other global variables in a fixed number of modules. How should I make sure that all the read happen after the set/update? Demo code: I want to have a GLOB at setting.py of module m: At m/setting.py: GLOB = dict() Some other modules (indefinitely many, assume they are p, q and r) will need to update this variable: At p/config.py: from m.setting import GLOB GLOB['p'] = 1 At q/config.py: from m.setting import GLOB GLOB['q'] = 2 At r/config.py: from m.setting import GLOB GLOB['r'] = 3 Two modules (fixed many, assume they are a and z) will need to read from this variable and do other stuff: At a/config.py: from m.setting import GLOB A_GLOB = [k for k in GLOB … -
Stop playing MIDI file on events
This is the script that I run from my Django App. It plays the .mdi file that the user uploads to the site. import pygame as pg def play_music(music_file): clock = pg.time.Clock() try: pg.mixer.music.load(music_file) print("Music file {} loaded!".format(music_file)) except pg.error: print("File {} not found! {}".format(music_file, pg.get_error())) return pg.mixer.music.play() # check if playback has finished while pg.mixer.music.get_busy(): clock.tick(30) def play(file): # pick a midi or MP3 music file you have in the working folder # or give full pathname # music_file = "/home/abhay/Desktop/moz2.mid" music_file = "/home/abhay/Desktop/Django/MusicApp/" + file #music_file = "Drumtrack.mp3" freq = 44100 # audio CD quality bitsize = -16 # unsigned 16 bit channels = 2 # 1 is mono, 2 is stereo buffer = 2048 # number of samples (experiment to get right sound) pg.mixer.init(freq, bitsize, channels, buffer) # optional volume 0 to 1.0 pg.mixer.music.set_volume(0.8) try: play_music(music_file) except KeyboardInterrupt: # if user hits Ctrl/C then exit # (works only in console mode) pg.mixer.music.fadeout(1000) pg.mixer.music.stop() raise SystemExit It exits only when the music is complete, or if I press Ctrl+C. But I need it to stop either by placing a button on the webpage, or a keyboard press event. It doesn't seem to be catching any events from what … -
Generating and storing unique ID using uuid in Django
In my project, I am trying to generate a unique user ID using python's uuid and then storing it in my mysql database.I am confused when I should generate the ID. This is my forms.py: from django import forms from django.contrib.auth.models import models from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm import uuid class RegistrationForm(UserCreationForm): email = models.EmailField(required=True) user_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class meta: model = User fields = ( 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] user.user_id = uuid.uuid4() if commit: user.save() return user This is the registration portion of my views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save return redirect('/account') else: form = RegistrationForm() args = {'form':form} return render(request, 'accounts/registration.html', args) -
Django: Annotate Max Multiple Queries
Here's my code, data1 = Data.objects.filter(...).annotate(Max('receiver')).order_by('-receiver__max') data2 = Data.objects.filter(...).annotate(Max('sender')).order_by('-sender__max') How can I combine these 2 queries in just one single Query? -
How can I deploy a django project in apache
How can I deploy a django project in apache, I am using Xampp and I have tried to configure the virtual host, the wsgi module and finally bitnami django and it does not work for me, urges me, if anyone has an idea of how I can make it work I am going to thank you, ahh I am Cuban, I do not have access to google and I can not download the module wsgi for apache, the one I have is pirate and I do not know if it works. Thank you -
graphite-manage + graphite warning
we installed graphite on our Linux server and after we installed the graphite and running it we saw the following warning from graphite-manage script graphite-manage syncdb --noinput /usr/lib/python2.7/site-packages/graphite/settings.py:246: UserWarning: SECRET_KEY is set to an unsafe default. This should be set in local_settings.py for better security warn('SECRET_KEY is set to an unsafe default. This should be set in local_settings.py for better security') Creating tables ... Installing custom SQL ... Installing indexes ... Installed 0 object(s) from 0 fixture(s how to avoid this warning ? what need to fix here ? -
Django bug on CRSF token
I am using django as web API for backend and React JS as web UI for frontend. User will sign up from web UI which will send a POST request to django to register with the user details. I want to protect the signup view with CSRF. Therefore I come out with steps below. First, once the sign up page is loaded, I fire a dummy GET request to store the csrf token with code below. handleSend(){ let req = { url: 'http://localhost:9000/vcubes/retrieve_token/', method : 'GET', withCredentials: true } axios(req) } Then, when user submit the signup form, another POST request will be fired. const data = JSON.stringify({ 'first_name': this.state.first_name, 'last_name': this.state.last_name, 'email': this.state.email, 'contact_number': this.state.contact_number, 'password1': this.state.password1, 'password2': this.state.password2, }) let req = { url: 'http://localhost:9000/vcubes/signup/', method : 'POST', headers: { 'Content-Type': 'text/plain' }, data: data } axios.defaults.headers.common['X-CSRF-TOKEN'] = this.getCookie('vcubes') With the code above, an OPTIONS will be sent to django first and then after django send back a 200 OK, then the actual POST request will be fired. Surprise! Django stated that I do not set CSRF cookie. Forbidden (CSRF cookie not set.): /vcubes/signup/ [30/Oct/2017 01:30:48] "POST /vcubes/signup/ HTTP/1.1" 403 2857 My settings.py is below. ( I only … -
Filtrar comentario por usuario logueado
Buenas tardes, Tengo dos tres modelos los cuales están relacionados entre sí; Perfil, Puesto y Tags. El perfil tira de AbstractUser el cual se utiliza para el registro del nuevo usuario. En este modelo se ha añadido una información adicional 'puesto de trabajo' que es creado con el otro modelo Puesto. models.py from django.db import models from django.contrib.auth.models import AbstractUser from apps.Tags.models import Tags class Puesto(models.Model): nombre_puesto = models.CharField(max_length=50) etiquetas = models.ManyToManyField(Tags, blank = True) def __str__(self): return '{}'.format(self.nombre_puesto) class Perfil(AbstractUser): nom_puesto = models.ForeignKey(Puesto, blank = True) def __str__(self): return '{}'.format(self.username) Por otra parte, el modelo de Tags está en otra aplicación, se muestra a continuación. models.py class Tags(models.Model): nombre = models.CharField(max_length=20) def __str__(self): return '{}'.format(self.nombre) Además tengo otra aplicación para crear comentarios con la posibilidad de añadirle también las etiquetas. El objetivo es conseguir mostrar sólo los comentarios que coincidan con los Tags del usuario, para ello: views.py class ComentarioListar (LoginRequiredMixin,ListView): login_url='/' redirect_field_name='redirigido' model = Comentario template_name = 'home/comentario_listar.html' def get_queryset(self): aa=Puesto.objects.filter(nombre_puesto=self.request.user.nom_puesto) return Comentario.objects.exclude(autor__id=self.request.user.id) b=Perfil.objects.filter(nom_puesto=self.request.user) c=Puesto.objects.filter(nombre_puesto=b) return Comentario.objects.filter(tag__id=c) Esto no funciona, por lo que me podrías echar una mano por favor? alguna idea de cómo puedo hacer que solo se visualicen los comentarios que contengan las etiquetas del usuario … -
NoReverseMatch Django favorite
I'm quite new to this Django stuff and i'm getting a NoReverseMatch at /cityinfo/ Exception Value: Reverse for 'user_favorites' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['cityinfo/(?P<fav_id>[0-9]+)/$'] basically what i'm trying to do is get all the users Favorited posts and display them when the user clicks on the favorite navigation link in base.html base.html <li class="#"> <a href="{% url 'cityinfo:user_favorites' fav_id.id %}"> <span class="glyphicon glyphicon-floppy-disk"></span>&nbsp; Favourites </a> </li> urls.py url(r'^(?P<fav_id>[0-9]+)/$', views.user_favorites, name="user_favorites"), views.py def user_favorites(request, fav_id): if not request.user.is_authenticated(): return render(request, 'cityinfo/login.html') else: favorites = get_object_or_404(user_favourite_spot, id=fav_id) context = { "favorites": favorites } return render(request, 'cityinfo/user_favorites.html', context) appreciate your help -
django celery delay function dont exetute
hello I want to use celery tasks in my Django project and I try to follow this very good tutorial from Mr.Vitor Freitas. but in my case and if try to run it that tutorial project i don't get results back the functions don't execute and in my case and in tutorial(i take message to wait and refresh and nothing after refresh). Any idea Why ? I think so the problem maybe is in RABBITQM server ?some configuration ? Just install Erlang(otp_win64_20.1.exe) and after RabbitMQ(rabbitmq-server-3.6.12.exe) here example code : settings.py CELERY_BROKER_URL = 'amqp://localhost' celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') app = Celery('mysite') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() tasks.py import string from django.contrib.auth.models import User from django.utils.crypto import get_random_string from celery import shared_task @shared_task def create_random_user_accounts(total): for i in range(total): username = 'user_{}'.format(get_random_string(10, string.ascii_letters)) email = '{}@example.com'.format(username) password = get_random_string(50) User.objects.create_user(username=username, email=email, password=password) return '{} random users created with success!'.format(total) _ _init_ _.py from .celery import app as celery_app __all__ = ['celery_app'] views.py from django.contrib.auth.models import User from django.contrib import messages from django.views.generic import TemplateView from django.views.generic.list import ListView from django.views.generic.edit import FormView from django.shortcuts import redirect from .forms import GenerateRandomUserForm from .tasks import create_random_user_accounts class … -
django modelform foreignkey update
I have my model as this: class Event(models.Model): EventId = models.UUIDField(primary_key=True) Winner = models.ForeignKey('Participant', on_delete=None) class Participant(models.Model): ID = models.UUIDField(primary_key=True) Name = models.CharField() I am trying to update an existing instance of the Event object using this in form.py class UpdateWinner(ModelForm): def __init__(self, *args, **kwargs): e = kwargs.pop('e', '') super(UpdateWinner, self).__init__(*args, **kwargs) self.fields['Winner'] = forms.ModelChoiceField(queryset=e)) class Meta: model = Event fields = '__all__' and in views.py def update_winner(request, event_id): if request.method == 'POST': form = UpdateWinner(request.POST, instance=Event.objects.get(EventId=event_id)) if form.is_valid(): else: event_par = Participant.objects.filter(some query) form = UpdateWinner(instance=event, e=event_par) I did check by printing the eventid, correct value is getting passed. but for some reason Winner field is causing some error with the form.is_valid() function and I am getting an error "'str' object has no attribute 'model'". Can anyone help me out here -
How to deny permission to a user of one kind from accessing the view of other user through url in django?
In my project, I've got different types of Users like this: User |-Client |-Employee |-Technical Manager |-Service Manager |-Production Manager No user can access the view of other user by url. A client cannot access profile of a Technical Manager through the url /officer/profile which is assigned for Technical Manager's profile. In order to do so, In my Client class in the models.py, I used this code snippet: class Client(models.Model): class Meta: permissions = ( ('view_client', 'view_Client'), ) Then for each view I used a decorator like this: @permission_required(lambda u: u.has_perm('authentication.view_client')) Then I'm logging in as a technical manager and trying to access with this url: /client/profile Then I got the error function object is not iterable. I was creating my user in an app called authentication. The models,py looks like this: ' @python_2_unicode_compatible class Profile(models.Model): user = models.OneToOneField(User) user_sex = (('MALE', 'Male'), ('FEMALE', 'Female')) sex = models.CharField(max_length=6, default='Male', choices=user_sex) address = models.CharField(max_length=250, null=True, blank=True) city = models.CharField(max_length=250, null=True, blank=True) state = models.CharField(max_length=250, null=True, blank=True) country = models.CharField(max_length=250, null=True, blank=True) phone = PhoneNumberField(blank=True) zip = models.IntegerField(null=True, blank=True) about = models.CharField(max_length=250, null=True, blank=True) email_confirmed = models.BooleanField(default=False) account_type = models.IntegerField(default=-1) class Meta: db_table = 'auth_profile' class Employee(models.Model): user = models.OneToOneField(User) manager = …