Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pycharm autocomplete doesn't work in conda env
I have python2/python3 env on my local machine. Python2 is installed in /usr/bin/python2.7, and python3 is installed with anaconda. I set up python3/Django2.0 project, set up isolated env for Django with anaconda. conda create --name Activated new env. source activate And installed dependencies with pip3 pip3 install -r requirements.txt Python, Django version: python --version: Python 3.6.4 :: Anaconda, Inc. django-admin.py version: 2.0.2 And, set python interpreter properly, as shown in the image. But, pycharm autocomplete is not working for me. Pycharm autocomplete doesn't work with pip installed packages in anaconda environment? Is this something you faced before? -
Django model QuerySet not returning when filtered
I'm not really sure what's happening here. I can see that I have a couple of emails in my database, but I can't seem to filter them. for example, when I run qs1 = EmailActivation.objects.all() >>> print(qs1) <EmailActivationQuerySet [<EmailActivation: a@yahoo.com>, <EmailActivation: b@gmail.com>]> however, when I run the following I get nothing qs2 = EmailActivation.objects.all().filter(email='a@yahoo.com') >>> print(qs2) <EmailActivationQuerySet []> my model looks like this: class EmailActivation(models.Model): user = models.ForeignKey(User) email = models.EmailField() I'd expect my qs2 to return 'a@yahoo.com' since it is in the database as seen by qs1. Does someone see what I'm doing wrong? Thanks, -
Django/python model form type error
I am getting a "quote_from_bytes() expected bytes" error when I am following the Django documentation for using Model form. It appears to write to the sqlite DB but every time I fill out the form it gives this error. forms.py from django.forms import ModelForm from .models import * class inputforms(ModelForm): class Meta: model = Inputform fields = ['auditid', 'audittask', 'responsibleperson', 'auditstatus', 'auditnotes', 'auditdate'] views.py def inputview(request): form = inputforms(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse, 'auditpage') args = {'form': form} # row = [str(s).encode() for s in {'form': form}] return render(request, 'auditentry.html', args) models.py class Inputform(models.Model): auditid = models.IntegerField(blank=True, null=True) audittask = models.TextField(blank=True, null=True) responsibleperson = models.TextField(blank=True, null=True) auditstatus = models.TextField(blank=True, null=True) auditnotes = models.TextField(blank=True, null=True) auditdate = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'inputform' -
Django - Query To Check if Item In Many to Many Relationship Field
I have a User and a Deal model as shown below. The User model has a 'favorites' field which is a many to many relationship with the Deal model. I'm trying to allow a user to save a Deal to their Favorites. I have tested both the favorite and remove_favorite views and both are doing exactly what they are supposed to do. Here's My Issue -- The conditional statement on my deal_detail.html page which checks to see if the current deal on the page is a favorite of the logged in user doesn't seem to be working. {% if deal_detail in user.favorites %} I'm just having a hard time wrapping my head around how to check this. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."}) username = models.CharField(max_length=40, default='') first_name = models.CharField(max_length=40, default='', blank=True) last_name = models.CharField(max_length=40, default='', blank=True) date_joined = models.DateTimeField(default=timezone.now) favorites = models.ManyToManyField(Deal, related_name='favorited_by', null=True, blank=True) class Deal(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=140, unique=True) description = models.TextField(default='') My corresponding views look like this: def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) user = request.user return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail, 'user': user}) @login_required(login_url='/accounts/sign_in/') def favorite(request, pk): if request.method == 'POST': favorite = Deal.objects.get(pk=pk) user = request.user … -
How to handle pagination in django templates and views?
I used bootstrap pagination in my templates. My productlist.html looks like this: <div> {% for i in products %} {% if i.is_published %} <div class="thumbnail"> <a href="{{ i.get_absolute_url }}"><img src="{{ i.thumb_url }}" alt="sample"/></a> <a href="{{ i.get_absolute_url }}"><p class="Content">{{ i.description }}</p></a> </div> <nav class="text-center"> <!-- Add class .pagination-lg for larger blocks or .pagination-sm for smaller blocks--> {% if contacts.has_other_pages %} <ul class="pagination"> {% if contacts.has_previous %} <li> <a href="?page={{ contacts.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> </a> </li> {% endif %} {% for i in page_range %} {% if contacts.number == i %} <li class="active"><a class="page_link" href="#">{{ i }} <span class="sr-only">(current)</span></a></li> {% else %} <li><a class="page_link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if contacts.has_next %} <li> <a href="?page={{ contacts.next_page_number }}" aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> {% else %} <li class="page-item disabled"> <a aria-label="Next"> <span aria-hidden="true">&raquo;</span> </a> </li> {% endif %} </ul> {% endif %} </nav> In my views: def product_list(request, category_slug=None): category = None products = Product.objects.filter(is_published=True) *** *** if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) *** *** paginator = Paginator(products, 5) page = request.GET.get('page') num_pages = paginator.num_pages try: contacts = paginator.page(page) … -
Migrating the Entry Model and TypeError: __init__() missing 1 required positional argument: 'on_delete'
Basically when setting up Django, I'm trying to migrate the entry model but I keep getting error with the activation of ll_env when typing python manage.py makemigrations learning_logs Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/ll_env/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/learning_logs/models.py", line 12, in <module> class Entry(models.Model): File "/Users/james/Desktop/The_Universe/CS/Python/Practice_PCC/learning_log/learning_logs/models.py", line 14, in Entry topic = models.ForeignKey(Topic) TypeError: __init__() missing 1 required positional argument: 'on_delete' Which should have showed like this as below from a book. (ll_env)learning_log$ python manage.py makemigrations learning_logs Migrations for 'learning_logs': 0002_entry.py: - Create model Entry (ll_env)learning_log$ python manage.py migrate Operations to perform: --snip-- Applying learning_logs.0002_entry... OK So basically the error, as TypeError shows, is that I missed … -
Django duplicate key violates unique constraint within transaction.atomic()
2018-03-06T23:57:28+00:00 app[postgres.20511]: [SILVER] [9-1] sql_error_code = 23505 ERROR: duplicate key value violates unique constraint "api_championitems_pkey" 2018-03-06T23:57:28+00:00 app[postgres.20511]: [SILVER] [9-2] sql_error_code = 23505 DETAIL: Key (champ_id)=(110) already exists. 2018-03-06T23:57:28+00:00 app[postgres.20511]: [SILVER] [9-3] sql_error_code = 23505 STATEMENT: INSERT INTO "api_championitems" ("champ_id", "item_blob") VALUES (110, '{}') I have a get_or_create wrapped within an atomic transaction and I have no idea why I am getting duplicate key errors. This is the only code that creates and writes to the UserChampionItems model. Also, is there a way to speed up this query? I am using postgres10 and django2.0 class UserChampionItems(models.Model): user_id = models.IntegerField() region = models.CharField(max_length=10) champ_id = models.IntegerField() lane = models.CharField(max_length=50) item_blob = models.TextField(default="{}") class Meta: unique_together = (("user_id", "region", "champ_id", "lane"),) @shared_task() def update_items(summoner_id, region, data): t = time.time() * 1000 for champ_id, lanes in data.items(): for lane, items in lanes.items(): with transaction.atomic(): uci, created = UserChampionItems.objects.select_for_update().get_or_create( user_id=summoner_id, region=region, lane=lane, champ_id=champ_id ) cur_data = ujson.loads(uci.item_blob) for item_id, occurence in items.items(): if item_id in cur_data: cur_data[item_id] += occurence else: cur_data[item_id] = occurence new_data = ujson.dumps(cur_data) uci.item_blob = new_data uci.save() print("ui:", time.time() *1000 - t) -
Django redirect from form to view in a different app
I have a django form that is now useless. I would like to always redirect from that form to a view in a different app. Here's what I have: return HttpResponseRedirect(reverse_lazy("management:management_account_add_user")) But I'm not sure where to put it. -
How I can integrate payment with maroc telecommerce in django-oscar?
I need to integrate payment method maroc telecommerce in django-oscar. -
Django display context variable (message) in template using .as_html
I am using some forms from django-graphos, and in order to draw the grpah, in the view def view(): make_your_data_somehow = [ [dataHeaders], [data1], [data2], etc… ] data_source = SimpleDataSource(data=make_your_data_somehow) your_chart = ChartType(data_source) return render(request, 'dataViewer.html', { 'chart' : your_chart, }) and in the template you would: <div> {{chart.as_html}} </div> <!-- the `chart` itself is a graphos object i think, it prints '<graphos.renderers.gchart.LineChart object at 0x107ecb190>' without `.as_html`--> In my case I need to have a certain data structure (more than one dataN in the example above). I can correctly detect if the data structure is correct in the view, but I am trying to avoid making an entirely new template for just one case (or restructuring for a template include). How do I make a variable have text that will be processed when called as variable.as_html in the view as actual text. I have tried: chart = 'Need more than one data to display Graph' chart = None a few others I can't retrace :\ but they all display nothing, unless I remove the .as_html in the template, which then would make displaying the graph non-existent. The only thing I know to do is to declare them as None … -
editing a slug post in django
I have an application where user create posts and can view them. the problem I face is with the edit button and how to make only users who created the post be able to edit their own post or delete them else another user can not. if I enter into the browser url field for example http://127.0.0.1:8000/soko/edit it opens the form field and it is ready to be edited but if I use input button from my template I get the following error Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['(?P<slug>[\\w-]+)/edit/$'] below is my views.py def edit(request, slug = None): instance = get_object_or_404(Post, slug = slug) form = PostForm(request.POST or None, request.FILES or None, instance = instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "Post updated") #redirecting to landing page return HttpResponseRedirect(instance.get_absolute_url()) context = { "title": instance.title, "instance": instance, "form": form, } template = 'edit.html' return render(request, template, context) def delete(request, slug=None): instance = get_object_or_404(Post, slug=slug) instance.delete() messages.success(request, "Post Deleted") return redirect(index) urls.py url(r'^(?P<slug>[\w-]+)/edit/$', views.edit, name='edit'), url(r'^(?P<slug>[\w-]+)/delete/$', views.delete, name='delete'), html <a class="btn btn-default" href="{% url 'posts:edit' %}"></a> futher codes would be supplied on request -
django_rest_swagger using http not https in "try it out" button
I'm using Django Rest Framework with Django Rest Swagger for API documentation. It seems that the "try it out" button always submits http requests, not https requests, even though the browser is https. I know how to do this if I rebuilt entire CoreAPI spec, but want to just pass something like protocol = 'https' to django_rest_swagger or something else that does not require re-coding the API documentation framework. -
Django view not recognizing request
I have a form that is filled out on a webpage. The goal of the form is to gather some basic info, and then save the IP of the sender to the DB too. The form submits a POST request to my Django view, but Django gives me the error: if request.method() == 'POST': TypeError: 'str' object is not callable Here is the view: from .form import SignUpForm from django.shortcuts import render from django.http import HttpResponseRedirect def index(request): if request.method() == 'POST': form = SignUpForm(request.POST) if form.is.valid(): signup_item = form.save(commit=False) signup_item.ip_address = request.META['HTTP_X_FORWARDED_FOR'] signup_item.save() return HttpResponseRedirect(request.path) else: form = SignUpForm() return render(request, 'index.html', {'form': form}) Here is the urls.py from django.conf.urls.import url from django.contrib import admin from form import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', views.index, name='home). ] -
Django Template syntax/tag to filter and check if a related data exists in that model
I'm working on a project with python-3.6.4 and django-2.0.2. For simplicity, I'm explaining the situation in short. Suppose, there are three apps:- "problems", "solve_activities" and "profiles" having three models(mentioned below) inside them. I have a "DetailView" page for each problem. I want to show if the logged in user has solved the problem or not. The django template tag that I wanted to do use was something like this: " {% if user.is_authenticated and problem.solved.objects.all.filter(solver={{user.username}}) %} " Here are the above mentioned files: "problems/models.py": class Problem(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(allow_unicode=True, max_length=100, unique=True) def __str__(self): return self.name def get_absoulte_url(self): return reverse('problems') return reverse('problems:problem_detail', kwargs={'slug':self.slug}) I've used the urlpatterns in 'problems/urls.py' as "path('/', views.ProblemDetail.as_view(), name='problem_detail')". "profiles/models.py"(inherited from auth.models.User): class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return self.username "solve_activities/models.py": class Solve(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE, related_name="solved") solver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="solved") I'm only creating this object when the user solves a problem. Now, my ProblemDetail view on problems/views.py: class ProblemDetail(generic.DetailView): model = Problem template_name = 'problems/problem_detail.html' And the "problems/problem_detail.html" file where I'm facing the complexity basically: <h1>{{problem}}</h1> <h4>Solve Status: {% if user.is_authenticated and problem.solved.objects.all.filter(solver={{user.username}}) %}Solved{% else %}Unsolved{% endif %}</h4> Again, {% if user.is_authenticated and problem.solved.objects.all.filter(solver={{user.username}}) %} this is what I want to do, … -
Django/Celery - SIGSEGV error accessing database
I have a Python-based Django app using the Celery task queue. I need to access my database, which I'm trying to do using the private key (See tasks.py). However, trying to access the database raises a segmentation fault error, and I'm not sure why. When I run this code directly from views.py, that is, I run dummyTask(user_model.id) rather than dummyTask.delay(user_model.id) the tasks runs to completion without any error messages. What could be causing this error with accessing my database? I looked at this question but couldn't find a solution. I'm running Python 3.6, Django 2.0.3 and celery 4.1.0 currently, and am also using db.sqlite3 with redis. The error message is: [2018-03-06 21:35:51,083: ERROR/MainProcess] Process 'ForkPoolWorker-1' pid:96231 exited with 'signal 11 (SIGSEGV)' [2018-03-06 21:35:51,097: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 11 (SIGSEGV).',) Traceback (most recent call last): File "/Users/rouskinlab/.pyenv/versions/3.6.0/envs/EMDC/lib/python3.6/site-packages/billiard/pool.py", line 1223, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 11 (SIGSEGV). The relevant code is: views.py ... from .forms import UserForm, SampleFormSet, StructureFormSet from .tasks import dummyTask def upload(request): # Create FormSets for validating uploads. StructureFormSet = formset_factory(StructureForm, formset=BaseLinkFormSet) LinkFormSet = formset_factory(LinkForm, formset=BaseLinkFormSet) if request.method == 'POST': display(request.POST) display('request POSTed... Checking form validity...') structure_formset = StructureFormSet(request.POST, request.FILES) #, … -
Serializer field named incorrectly
I'm attempting to present some serialized data, and am getting a AttributeError when attempting to get a value for field name. models.py: class Resource(models.Model): """Initial representation of a resource.""" # ID from fixture resources, for internal dedupe internal_id = models.CharField(max_length=20, null=True, blank=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) categories = models.ManyToManyField("Category") neighborhoods = models.ManyToManyField("Neighborhood") email_contact = models.EmailField(null=True, blank=True) pdf = models.ManyToManyField("PDF") phone = models.CharField(max_length=200, blank=True, null=True) website = models.URLField(max_length=200, blank=True, null=True) # address street_address = models.CharField(max_length=400, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=10, null=True, blank=True) latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) zip_code = models.CharField(max_length=10, null=True, blank=True) # meta created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def __unicode__(self): return u'{}'.format(self.name) @property def categories_str(self): return [str(t) for t in self.categories.all()] @property def neighborhoods_str(self): return [str(t) for t in self.neighborhoods.all() if t] or ["Houston"] @property def bookmark(self): """This is here to make it easier to serialize a standard resource.""" return getattr(self, "_bookmark", None) @bookmark.setter def bookmark(self, bookmark): self._bookmark = bookmark def indexing(self): safe_zip = str(self.zip_code or "") safe_neighborhood = [n for n in self.neighborhoods.all() if n] or ["Houston"] obj = ResourceDoc( meta={"id": self.id}, name=self.name, resource_suggest=self.name, email_contact=self.email_contact, phone=self.phone, description=self.description, website=self.website, categories=self.categories_str, street_address=self.street_address, city=self.city, state=self.state, zip_code=safe_zip, … -
HTML templates not getting rendered in django
I am new at django and I have an app in django project. My base.html has navigation bar through which you can redirect to "about", 'contact us', 'home'. The first page when app starts (after loging in) is home. <!DOCTYPE html> <html lang="en"> <head> {%load staticfiles%} <meta charset="utf-8"> <title>Ekyam: India's First Entrepreneurial Ecosystem</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="" name="keywords"> <meta content="" name="description"> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900" rel="stylesheet"> <!-- Bootstrap CSS File --> <link href="{% static "visit/lib/bootstrap/css/bootstrap.min.css" %}" rel="stylesheet"> <!-- Libraries CSS Files --> <link href="{% static "visit/lib/font-awesome/css/font-awesome.min.css"%}" rel="stylesheet"> <link href="{% static "visit/lib/owlcarousel/owl.carousel.min.css" %}" rel="stylesheet"> <link href="{% static "visit/lib/owlcarousel/owl.theme.min.css"%}" rel="stylesheet"> <link href="{% static "visit/lib/owlcarousel/owl.transitions.min.css" %}" rel="stylesheet"> <!-- Main Stylesheet File --> <link href="{%static "visit/css/style.css"%}" rel="stylesheet"> <!--Your custom colour override - predefined colours are: colour-blue.css, colour-green.css, colour-lavander.css, orange is default--> <link href="#" id="colour-blue" rel="stylesheet"> </head> <body class="page-index has-hero"> <!--Change the background class to alter background image, options are: benches, boots, buildings, city, metro --> <div id="background-wrapper" class="city" data-stellar-background-ratio="0.1"> <!-- ======== @Region: #navigation ======== --> <div id="navigation" class="wrapper"> <!--Hidden Header Region--> <div class="header-hidden collapse"> <div class="header-hidden-inner container"> <div class="row"> <div class="col-md-3"> <h3> About Us </h3> <p>Ekyam is dedicated to support and nourish Startups and accelaration</p> <a href="about.html" class="btn btn-more"><i class="fa … -
Issue with urls re_path
I have the following url re_path: re_path(r'^up_account/(?P<ud>[0-9A-Za-z_\-]+)/(?P<tk>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', AccountView.as_view(), name='up_account'), path('accounts/', include('users.urls', namespace='users')), I called in a template this way: {% url 'users:up_account' ud=ud tk=tk %} I have the following error: Reverse for 'up_account' with keyword arguments '{'ud': b'MjA', 'tk': '4u9-15b083b81757413cf575'}' not found. 1 pattern(s) tried: ['accounts\\/up_account/(?P<ud>[0-9A-Za-z_\\-]+)/(?P<tk>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] "accounts\" - I think is because I'm on windows and print does it this way -
I need to add form files as model instances dynamically in django
I'm trying to do something like this: There's a form in my web page and has a "select files button" so you can upload multiple files at once. My problem is that I need "get" that files and add each of them to be a model instance, is there possible? -
Django Rest Framework: AttributeError: 'NoneType' object has no attribute '_meta' [for OneToOneField]
I need help with a POST request using Django rest framework. I have a User model that inherits from AbstractBaseUser which has 2 fields: name and email. Then I have a DojoMaster model that has a OneToOne relationship with the User model: class DojoMaster(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) phone = models.BigIntegerField() country = models.ForeignKey(Country, on_delete=models.CASCADE) I want to register the dojo master via an API so I created the following serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('name', 'email', 'password') class DojoMasterCreateSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = DojoMaster fields = ('user', 'phone', 'country') def create(self, validated_data): validated_data['country'] = Country.objects.get( country=validated_data['country']) user_data = validated_data.pop('user') user = UserSerializer.create(UserSerializer(), validated_data=user_data) subscriber, created = DojoMaster.objects.update_or_create(user=user, phone = validated_data.pop('phone'), country = validated_data['country']) return subscriber To call on these serializers, I created the following view: class DojoMasterCreateView(generics.CreateAPIView): def post(self, request, format='json'): serializer = DojoMasterCreateSerializer(data=request.data) if serializer.is_valid(raise_exception=ValueError): serializer.create(validated_data=request.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) For the body of the POST request I had the following: { "user": { "name": "XYZ", "email": "xyz@mail.com", "password": "8Xa,9Lv&" }, "phone": 9696510, "country": "USA" } However, when I do that I get the following error: Traceback (most recent call last): File "C:\Users\app_dev\Envs\game_of_quarks\lib\site-packages\django\core\handlers\exception.py", line 41, in inner … -
(Django) Cannot update custom profile
So I'm trying to update the user's info in an extended update, but it worked before I added the rest, but now it won't work I've tried going back still nothing. it's not taking it as its even POST Requesting when clicking submit why tho? Html <form xaction="{% url 'userprofileupdate' logged_in_user.pk %}" method="POST"> {% csrf_token %} https://pastebin.com/vMw6AEai (only Pastebin because of its a lot of code) Views.py @login_required def userprofileupdate(request, user_pk): if request.method == 'POST': form = UpdateProfileForm(request.POST, instance=request.user) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.extendeduser.nickname = form.cleaned_data.get('username') user.extendeduser.postal_code = form.cleaned_data.get('postal_code') user.extendeduser.phone_number = form.cleaned_data.get('phone_number') user.extendeduser.emergency_number = form.cleaned_data.get('emergency_number') user.extendeduser.birthdate = form.cleaned_data.get('birthdate') user.extendeduser.languages = form.cleaned_data.get('languages') user.extendeduser.drivers_licence = form.cleaned_data.get('drivers_licence') user.extendeduser.tshirt = form.cleaned_data.get('tshirt') user.extendeduser.special_considerations = form.cleaned_data.get('special_considerations') user.save() messages.success(request, "Your profile has been updated!") return redirect('usersettings', user_pk=request.user.pk) messages.error(request, 'Error: please update your settings if you want to update them') return redirect('usersettings', user_pk=request.user.pk) forms.py class UpdateProfileForm(forms.ModelForm): postal_code = forms.CharField(max_length=10, required=True) phone_number = forms.CharField(max_length=16, required=True) emergency_number = forms.CharField(max_length=16, required=True) birthdate = forms.DateField(required=False) languages = forms.MultipleChoiceField(required=False) drivers_licence = forms.MultipleChoiceField(required=False) tshirt = forms.ChoiceField(required=False) special_considerations = forms.CharField(required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'birthdate', 'phone_number', 'emergency_number', 'postal_code', 'languages', 'drivers_licence', 'tshirt', 'special_considerations',) -
Count True or False (1 or 0) values from database in Django template
I am trying to implement user template view to show how many devices are online and how many are offline. For that instance I am storing in database column 'status' with values of 1 and 0. I could not figure it out how to take these values and count them in Django environment. I mean if i have 4 True(1) values, in template it should look like: You have 4 online devices and vise versa if there are 4 False(0) values it should look like: You have 4 offline devices Is it possible to make it happen in Django? I'm really a rookie in this field and would really appreciate some good tips... my models.py class Device(models.Model): usr = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ip = models.CharField(max_length=50) status = models.IntegerField(default=0) -
Query db in Django for one row with a pair of values
I want to query DB in my views.py to retrieve one pair of values from two columns only. Let me show you my efforts: Items.objects.filter(file_name=name).values('file_name', 'secret') I need exactly one pair of values coming from columns called: 'file_name' and 'secret'. Value of 'secret' has to be in the same raw of 'file_name' How could I write such query? What data type is it going to return? -
Local postgis DB setup for Geodjango
I've been trying to setup my (windows) computer such that I can have a local postgreSQL with PostGIS extension. With this installed I hope to be able to create a project with geodjango locally before putting it in the cloud. I have been working with Django for a little while now on my local machine with the SQLite DB, but since the next project will partly be based on coordinate based data I wanted to setup the right environment. I've tried to follow most of the geodjango information/tutorials online, but can't get it to work. What I've done (mostly followed this: https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/#windows): Download and install the latest (10.3) PostgreSQL setup from https://www.enterprisedb.com/downloads/postgres-postgresql-downloads After installation I also installed used the Application Stack Builder to install PostGis I've installed OSGeo4W from https://trac.osgeo.org/osgeo4w/ I've created a batch script as described on the geodjango website (https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/#windows) and ran it as administrator (except for the part where it sets the path to python, cause python was already in there since I've been using python for a while now) I've tried some command in psql shell and I think I've created a database with name: geodjango, username: **** and pass: ****. I don't know if I … -
Library for editing images with different effects in Django, Python
I am looking to apply all possible effects to an uploaded image. I need to figure out that, is there any third party packages or Python libraries to edit the image uploaded with different effects. And how to approach as per it.