Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: How to resolve python setup.py egg_info failed with error code 1
I'm stuck with a project in Django where I have to install MySQL-python. When I'm running pip install MySQL-Python I got this error: Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-Ue6URf/MySQL-Python/ I used brew as suggested in some answers here but didn't help at all. I'm using a Mac machine with the last Python3 and the last Django version. I have MampPro last version which I'm using the MySQL service. I'm sharing the entire output of the installation: Collecting MySQL-Python Downloading MySQL-python-1.2.5.zip (108kB) 100% |################################| 112kB 561kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/tmp/pip-build-Ue6URf/MySQL-Python/setup.py", line 17, in <module> metadata, options = get_config() File "setup_posix.py", line 53, in get_config libraries = [ dequote(i[2:]) for i in libs if i.startswith(compiler_flag("l")) ] File "setup_posix.py", line 8, in dequote if s[0] in "\"'" and s[0] == s[-1]: IndexError: string index out of range ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-Ue6URf/MySQL-Python/ -
NoReverseMatch at /groups/ Reverse for 'single' with keyword arguments '{'slug': 'first-group'}' not found
I'm so lost, my code matches exactly to this tutorial I'm following (I've triple checked) and yet I can't seem to find the issue. I am trying to have all my social network's group display on a page and that page should be the groups_list.html page. I have checked all over stack overflow for a similar problem and no one seems to have an issue like this. Views.py from django.shortcuts import render from django.contrib import messages from django.contrib.auth.mixins import (LoginRequiredMixin,PermissionRequiredMixin) from django.core.urlresolvers import reverse from django.views import generic from django.shortcuts import get_object_or_404 from groups.models import Group,GroupMember # Create your views here. class CreateGroup(LoginRequiredMixin,generic.CreateView): fields = ('name','description') model = Group class SingleGroup(generic.DetailView): model = Group class ListGroup(generic.ListView): model = Group class JoinGroup(LoginRequiredMixin,generic.RedirectView): def get_redirect_url(self,*args,**kwargs): return reverse('groups:single',kwargs={'slug':self.kwargs.get('slug')}) def get(self,request,*args,**kwargs): group = get_object_or_404(Group,slug=self.kwargs.get('slug')) try: GroupMember.objects.create(user=self.request.user,group=group) except: messages.warning(self.request,"Warning: You are already a member of this group") else: messages.success(self.request,"Your are now a member!") return super().get(request,*args,*kwargs) class LeaveGroup(LoginRequiredMixin,generic.RedirectView): def get_redirect_url(self,*args,**kwargs): return reverse('groups:single',kwargs={'slug':self.kwargs.get('slug')}) def get(self,request,*args,**kwargs): try: membership = models.GroupMember.objects.filter( user = self.request.user, group__slug = self.kwargs.get('slug') ).get() except models.GroupMember.DoesNotExist: messages.warning(self.request,"You can't leave a group you are not a member of") else: membership.delete() messages.success(self.request,"You have left this group!") return super().get(request,*args,**kwargs) urls.py #GROUPS URLS.PY from django.conf.urls import url from groups … -
Django Querysets -& select_related: unable to retrieve a set of foreignkey objects
I'm sure I'm doing something very stupid here as this isn't a complex issue and in other frameworks it's not a problem. class ArticlePage(Page): ... city = models.ForeignKey(City, on_delete=models.PROTECT, null=True) ... Then in a view: qs = ArticlePage.objects.filter(city__isnull=False).filter(city__name__icontains=self.q).select_related('city') So I've tried many permutations of the above query, and none of them return the desired result. All the results are a set of ArticlePage type instead of City. All I'm trying to do is return a set of results of type City that contains every City object that is referenced by an ArticlePage, but I'm going insane trying to make this happen with django querysets, and I'm sure I'm just doing something very silly. Appreciate any advise here. -
Forward Many to One Descriptor attribute error Django
I am new to django what am I doing wrong here? I want to delete a song from an album and I want to redirect it to the album details page. class SongDelete(DeleteView): model = Song album_id = Song.album.pk success_url = reverse_lazy('music:detail', args=[album_id]) -
Customizing Django User model yields error
I have created a custom User model inheriting from the Django one in models.py: from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token # Create your models here. class User(AbstractUser): pass # triggered as soon as a new user is saved in the db @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) Following this link, I also add my app to INSTALLED_APP and change AUTH_USER_MODEL in settings.py: """ Django settings for WestMolkkyClubBackend project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '******************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.0.12'] AUTH_USER_MODEL = 'WestMolkkyClubBackend.User' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'WestMolkkyClubBackend' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'WestMolkkyClubBackend.urls' TEMPLATES = … -
ModelForm saving over model data with empty fields
I'm building an Edit form for a model in my database using a ModelForm in Django. Each field in the form is optional as the user may want to only edit one field. The problem I am having is that when I call save() in the view, any empty fields are being saved over the instance's original values (e.g. if I only enter a new first_name, the last_name and ecf_code fields will save an empty string in the corresponding instance.) The form: class EditPlayerForm(forms.ModelForm): class Meta: model = Player fields = ['first_name', 'last_name', 'ecf_code'] def __init__(self, *args, **kwargs): super(EditPlayerForm, self).__init__(*args, **kwargs) self.fields['first_name'].required = False self.fields['last_name'].required = False self.fields['ecf_code'].required = False The view: def view(request, player_pk = ''): edit_player_form = forms.EditPlayerForm(auto_id="edit_%s") if "edit_player_form" in request.POST: if not player_pk: messages.error(request, "No player pk given.") else: try: selected_player = Player.objects.get(pk = player_pk) except Player.DoesNotExist: messages.error(request, "The selected player could not be found in the database.") return redirect("players:management") else: edit_player_form = forms.EditPlayerForm( request.POST, instance = selected_player ) if edit_player_form.is_valid(): player = edit_player_form.save() messages.success(request, "The changes were made successfully.") return redirect("players:management") else: form_errors.convert_form_errors_to_messages(edit_player_form, request) return render( request, "players/playerManagement.html", { "edit_player_form": edit_player_form, "players": Player.objects.all(), } ) I've tried overriding the save() method of the form to … -
Django ModelForm to update profile picture does not save the photo
I want to enable my users to change their profile picture. When uploading a photo, I am redirected to the success page but the photo is not uploaded to the folder and the associated field is blank. Note that if a user already had a photo, it resets the field to blank so after submitting the form, the user has no photo anymore. My guess is that the form.save(commit=False) does not upload the photo nor update the field as it should but I do not understand why ! Here is the model, view and form : The Profil model: class Profil(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) photo_profil=models.ImageField(null=True,blank=True,upload_to='img/profils', verbose_name="Photo de profil", help_text="La taille du fichier doit être inférieure à {0}Mo. Seules les extensions .png, .jpeg et .jpg sont acceptées.".format(str(int(MAX_UPLOAD_SIZE/1000000)))) cours_valides=models.CharField(blank=True,max_length=255,validators=[int_list_validator]) niveau_valides=models.CharField(blank=True,max_length=255,validators=[int_list_validator]) def __str__(self): return "Profil de {0}".format(self.user.username) The ModelForm: class PhotoForm(forms.ModelForm): class Meta: model=models.Profil fields=('photo_profil',) def clean_photo(self): photo=self.cleaned_data.get('photo_profil') if photo.size>settings.MAX_UPLOAD_SIZE: raise forms.ValidationError(_("Le fichier envoyé depasse la limite de %sMo.".format(str(settings.MAX_UPLOAD_SIZE/1000000)))) return photo And the view : @login_required() def change_photo(request): if request.method=="POST": form=forms.PhotoForm(request.POST,request.FILES) if form.is_valid(): profil=form.save(commit=False) profil.user=request.user profil.save() return redirect('espace_personnel') else: form=forms.PhotoForm() return render(request,'utilisateurs/registration/change_photo.html',{'form':form}) Finally the template: {% block item %} <h3> Modifier sa photo de profil </h3> <hr> <div class="row"> <div class="col-lg-4"> <img src="{{user.profil.photo_profil_url}}" … -
Django not creating table for custom user
I've been trying to create a custom user to store extra fields in Django, but after specifying the new User and deleting the old database, Django does not want to make a table or any migrations for my app "accounts" Error (when doing anything user related e.g. logging in): django.db.utils.OperationalError: no such table: accounts_user Auth User Model in settings.py: AUTH_USER_MODEL = 'accounts.User' Installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'forum', ] accounts/models.py: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass -
Django: object has no attribute 'was_published_recently' - except it does
Similar but not the same problem as this post. New to Django, I've been doing the 1st tutorial and I'm at part 5 now, which is automated testing. After following the tutorial until step "Fixing the Bug", it pops up an error when I run the test, as follows: Creating test database for alias 'default'... E ====================================================================== ERROR: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/ian/mysite/polls/tests.py", line 18, in test_was_published_recently_with_future_question self.assertIs(future_question.was_published_recently(), False) AttributeError: 'Question' object has no attribute 'was_published_recently' ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) Destroying test database for alias 'default'... Here's my code: tests.py import datetime from django.utils import timezone from django.test import TestCase from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() returns False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) models.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): def __str__(self): return self.choice_text question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) -
Django-Gunicorn-Nginx deployement doesn't get past Nginx
I'm trying to deploy a project on an EC2 instance. When I go to my EC2 instance URL, I can see Nginx welcome message, but I can't seem to roll it into django. I have a Gunicorn service up and Nginx service up, these are the outputs of their service status calls: Gunicorn: ● gunicorn_mynew_website.service - Gunicorn daemon for mynew website Loaded: loaded (/etc/systemd/system/gunicorn_mynew_website.service; enabled; vendor preset: enabled) Active: active (running) since Sat 2017-08-19 12:29:05 UTC; 2s ago Main PID: 1760 (gunicorn) Tasks: 2 Memory: 33.6M CPU: 368ms CGroup: /system.slice/gunicorn_mynew_website.service ├─1760 /opt/mynew/venv/website-venv/bin/python3.5 /opt/mynew/venv/website-venv/bin/gunicorn website.wsgi:application --name website --workers 1 --user ubuntu --bind=unix:/opt/mynew/run/gunicor └─1769 /opt/mynew/venv/website-venv/bin/python3.5 /opt/mynew/venv/website-venv/bin/gunicorn website.wsgi:application --name website --workers 1 --user ubuntu --bind=unix:/opt/mynew/run/gunicor Aug 19 12:29:05 ip-172-31-26-24 systemd[1]: Started Gunicorn daemon for mynew website. Aug 19 12:29:05 ip-172-31-26-24 gunicorn_start.sh[1760]: Starting website as ubuntu Aug 19 12:29:05 ip-172-31-26-24 gunicorn_start.sh[1760]: [2017-08-19 12:29:05 +0000] [1760] [INFO] Starting gunicorn 19.7.1 Aug 19 12:29:05 ip-172-31-26-24 gunicorn_start.sh[1760]: [2017-08-19 12:29:05 +0000] [1760] [INFO] Listening at: unix:/opt/mynew/run/gunicorn.sock (1760) Aug 19 12:29:05 ip-172-31-26-24 gunicorn_start.sh[1760]: [2017-08-19 12:29:05 +0000] [1760] [INFO] Using worker: sync Aug 19 12:29:05 ip-172-31-26-24 gunicorn_start.sh[1760]: [2017-08-19 12:29:05 +0000] [1769] [INFO] Booting worker with pid: 1769 Nginx ● nginx.service - A high performance web server and a reverse proxy … -
Django django-autocomplete-light not showing results
I want to learn python and web-dev and I am trying to make a functional web application. Right now I have problem with django-autocomplete-light. I am trying to use autocomplete for my django application. I followed the tutorial, but when I try to search It says that The results could not be loaded. But results are shown in dropdown list. I have a form where user can add new invoce, I am trying to use django-autocomplete-light for autocompleting all suppliers so user, doesn't need to search for it. My models: class Supplier(models.Model): supp_name = models.CharField(max_length=255) mat_number = models.CharField(max_length=255) organ = models.CharField(max_length=255, null=True, blank=True) street = models.CharField(max_length=255, null=True, blank=True) email = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.supp_name.encode("utf-8") def get_absolute_url(self): return reverse('supplier-detail', args=[str(self.id)]) def __unicode__(self): return '%s' % (self.supp_name,) class Invoice(models.Model): organization = models.ForeignKey(Group, help_text="organization") input_peo = models.CharField(max_length=150) date = models.DateTimeField(auto_now_add=True) supplier = models.ForeignKey(Supplier, on_delete=models.SET_NULL, null=True, related_name='name') invoice_number = models.CharField(max_length=100, null=True, blank=True, help_text='Številka preračuna') price = models.FloatField(null=True, blank=True, help_text='Cena brez DDV') sum_me = models.IntegerField(null=True, blank=True, help_text='Kolicina') def __str__(self): return self.organization.name.encode("utf-8") def get_absolute_url(self): return reverse('invoice-detail', args=[str(self.id)]) My views: class AddInvoice(LoginRequiredMixin, generic.View): login_url = '/accounts/login/' redirect_field_name = 'redirect_to' form_class = InvoiceCreate template_name = 'invoce/invoce_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, … -
"conversion from method to Decimal is not supported django" error
So, I'm trying to calculate the coffee price of the parameters mentioned below. But, every time I try to call the coffeeprice method, it gives me a conversion from method to Decimal is not supported error. I have the following code in my view and model respectively: def order(request): if not (request.user.is_authenticated): raise Http404 order_form = OrderForm(request.POST or None) if order_form.is_valid(): obj = order_form.save(commit=False) obj.price = Decimal(obj.coffeeprice) obj.save() messages.success(request, "Thank you for your order.") return redirect("arabica:list") context = { "order_form": order_form, } return render(request, 'order.html', context) class Coffee(models.Model): ONE = 1 TWO = 2 THREE = 3 FOUR = 4 FIVE = 5 shots_choices = ( (ONE, 'One'), (TWO, 'Two'), (THREE, 'Three'), (FOUR, 'Four'), (FIVE, 'Five'), ) user = models.ForeignKey(User, default=1) name = models.CharField(max_length=50) bean_type = models.ForeignKey(CoffeeBean) roast_type = models.ForeignKey(Roast) shots_number = models.IntegerField(default=ONE, choices=shots_choices) syrup_type = models.ManyToManyField(Syrup) powder_type = models.ManyToManyField(Powder) water = models.FloatField() milk = models.BooleanField(default=False) foam = models.FloatField() extra_instructions = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=3) completed = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def coffeeprice(self): total = 0 total += self.bean_type.price total += self.roast_type.price for syrup in self.syrup_type.all(): total += syrup.price for powder in self.powder_type.all(): total += powder.price if self.milk: milk_price = .25 total += milk_price shots_price = self.shots_number * … -
Python ccavutil module not found
I can't find ccavutil module in Python 3.6.How to install it.I have installed Django and pycrypto but still I have module not found error.How to install this module.Thanks a lot. P.S.:This what python says: >>> import ccavutil Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'ccavutil' -
Adding multiple device tokens for a single userId
I am creating a notification server for my app . I want to add multiple device tokens for a single userId. Currently when a user logins from a new device his previous device token is deleted. This way if he is using two devices simultaneously he will get notification in one device only. How can I store multiple device tokens for that particular user so that he gets notification on both of his devices. -
Django Model Forms AttributeError while setting instance value
I want to set profile's avatar, but I get an error while updating object: 'Profile' object has no attribute 'profile' I've created a model: models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='profile') slug = models.SlugField(editable=False, unique=True) avatar = models.ImageField(upload_to=get_upload_avatar, null=True, blank=True) And Model Form: froms.py from PIL import Image class AvatarForm(ModelForm): class Meta: model = Profile fields = ['avatar',] def save(self): avatar = super(AvatarForm, self).save() im = Image.open(avatar.file) resized_image = im.thumbnail(64, 64) resized_image.save(avatar.file.path) return avatar Template rendering as usual: template.html <form action="{% url 'avatar_add' me.slug %}" enctype="multipart/form-data" method="POST"> {% csrf_token %} {% render_field avatar_form.avatar class="form-control form-control-sm" accept="image/*" onchange="this.form.submit()"%} </form> And url reciever: urls.py url(r'^profile/(?P<slug>[-\w]+)/avatar_add$', AddAvatar, name='avatar_add'), The handling view: @login_required def AddAvatar(request, slug): if request.method == 'POST' and request.FILES['avatar'] and request.user.profile.slug == slug: form_avatar = AvatarForm(request.POST, request.FILES) if form_avatar.is_valid(): profile = Profile.objects.get(slug=slug) profile.avatar = form_avatar.cleaned_data['avatar'] profile.save() # <--get err here return HttpResponse(form_avatar.cleaned_data['avatar']) While saving profie I get error as above. Another problem is that def save() function will be never called, because I'm not saving ModalForm() instance, but just using it to update something other. I'm newbie in Django, please help. -
Asset bundling with Django pipeline
I dont have much experience with Django mostly with Grails. I am trying to make a single page app that uses an API. I have both the API and the app javascripts as 2 django apps in the same django project. When i use this configuration: STATIC_URL = '/static/' STATIC_ROOT = os.path.normpath(os.path.join(BASE_DIR, 'static')) STATICFILES_DIRS = [os.path.normpath(os.path.join(BASE_DIR, 'extra_static'))] # Django Pipeline (and browserify) STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = [ 'pipeline.finders.PipelineFinder', 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] # browserify-specific PIPELINE_COMPILERS = ( 'pipeline_browserify.compiler.BrowserifyCompiler', ) if DEBUG: PIPELINE_BROWSERIFY_ARGUMENTS = '-t babelify' PIPELINE = { # 'PIPELINE_ENABLED': True, 'CSS_COMPRESSOR': 'pipeline.compressors.NoopCompressor', 'JS_COMPRESSOR': 'pipeline.compressors.yuglify.YuglifyCompressor', 'STYLESHEETS': { 'frontend': { 'source_filenames': ( 'css/style.css', ), 'output_filename': 'css/frontend.css', 'extra_context': { 'media': 'screen,projection', }, } }, 'JAVASCRIPT': { 'frontend': { 'source_filenames': ( 'js/bower_components/jquery/dist/jquery.min.js', 'js/bower_components/react/react.min.js', 'js/frontend.browserify.js', ), 'output_filename': 'js/frontend.js', } } } I get these requests which are all successful but no bundling whatsoever has happened. [19/Aug/2017 12:56:25] "GET /web/ HTTP/1.1" 200 876 [19/Aug/2017 12:56:25] "GET /static/css/style.css HTTP/1.1" 200 39 [19/Aug/2017 12:56:25] "GET /static/js/bower_components/react/react.min.js HTTP/1.1" 200 23040 [19/Aug/2017 12:56:25] "GET /static/js/frontend.browserify.js HTTP/1.1" 200 349 [19/Aug/2017 12:56:25] "GET /static/js/bower_components/jquery/dist/jquery.min.js HTTP/1.1" 200 86659 If i un-comment the first line in the PIPELINE configuration object I do see that the bundled assets are used instead but this time … -
Custom Middleware get_response not working
I am just trying to run django with a custom Middleware. As of now the get_response returns a 500 status while displaying the home page. In case the user is a normal user and not a tenant, I wanted the app to run normally. I've just started but the get_response function which I suppose is to show responses as executed by other middlewares later results in 500 status. Any help trying to figure out, how I could use my custom middleware is appreciated. class TenantMiddleware(MiddlewareMixin): def process_request(self, request): absolute_url = request.get_full_path() url = urlparse.urlparse(absolute_url) print absolute_url print url subdomain = url.hostname.split(".") if url.hostname else None if subdomain and subdomain != 'affectlab' : if 'subdomain' not in request.session: print "I am here" tenant=map(lambda x : x[0],(list(profiles.models.Tenant.objects.filter(name=subdomain).values_list('id')))) if tenant: request.session['tenant'] = int(tenant[0]) request.session['subdomain'] = subdomain.strip() return HttpResponseRedirect("/login/") else: response = render_to_response('404.html', {},context_instance=RequestContext(request)) response.status_code = 404 return response else: if request.session['subdomain'] == subdomain: return self.get_response(request) else: tenant = map(lambda x: x[0],(list(profiles.models.Tenant.objects.filter(name=subdomain)).values_list('id'))) if tenant: request.session['tenant'] = int(tenant[0]) request.session['subdomain'] = subdomain.strip() response = logout(request) # ,next_page=reverse("/")) return HttpResponseRedirect("/login/") else: response = render_to_response('404.html', {}, context_instance=RequestContext(request)) response.status_code = 404 return response else: try : response = self.get_response(request) except Exception as e: print e.message return response -
Django - multiple url routers, same url?
So i am trying to have a server control page in a django applications with a list of servers that links via uuid to starting, cloning and stopping each respective server. (think a really terrible openstack UI). This is the code that generates the url. <li><a href="{% url 'start' uuid=uuid %}">Start</a></li> <li><a href="{% url 'clone' uuid=uuid %}">Clone</a></li> <li><a href="{% url 'stop' uuid=uuid %}">Stop</a></li> Unfortunately it would appear that when I click the clone link on the web application it starts rather than clones the server, meaning it is running the start function in view. Here is how the urls are defined: urlpatterns = [ url(r'^$', views.index, name='index'), #url(r'^$', views.transfer, name='transfer'), url(r'^malware/$', views.malware, name='malware'), # Add this /malware/ route url(r'^about/$', views.about, name='about'), # Add this /about/ route url(r'^(?P<uuid>[\w\-]+)$', views.start, name='start'), url(r'^(?P<uuid>[\w\-]+)$', views.paranoidfish, name='paranoidfish'), url(r'^(?P<uuid>[\w\-]+)$', views.clone, name='clone'), url(r'^(?P<uuid>[\w\-]+)$', views.stop, name='stop'), url(r'^(?P<uuid>[\w\-]+)$', views.transfer, name='transfer'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I'm sure there's something basic i'm missing here, as always any help would be appreciated. -
django delete model entry from selected form option
I have the following form displaying entries of a model for user settings. When selected, I would like that a button catches its pk and send it to a Delete view.Here is the current code but I am missing this part. html <form id="SettingsListForm"><label>&nbsp Settings List : &nbsp &nbsp &nbsp</label> {% if user.usersetting.first %} <select class="form-control" name="settingslist" id = "settingslist" form="SettingsListForm" > {% for settings in user.usersetting.all %} <option value="{{ settings.file.url }}">{{ settings }} </option> {% endfor %} </select> {% else %} <li class="list-group-item">NO SETTINGS YET</li> {% endif %} <button class="btn btn-outline-light btn-circle"><i class="glyphicon glyphicon-minus" href="{% url 'my_app:setting_delete' pk=user.usersetting.last.id %}"></i></button> {% block delete_setting_confirm_block %} {% endblock %} </form> my_app urls url(r'^setting/(?P<pk>\d+)/$',views.UserSettingDeleteView.as_view(),name='setting_delete'), -
Django: URL error in category model
I created a simple category model. The models I created are as follows. Where do I make mistakes in these model files? Thanks for your help. models.py The code I added to the file is as follows. class Category(models.Model): category_name = models.CharField(max_length=250) category_desc = models.TextField() slug = models.SlugField(max_length=250, unique=True) class Meta: ordering = ('category_name',) verbose_name = 'category' verbose_name_plural = 'Categories' def get_absolute_url(self): return reverse('article:categories', args=[self.slug]) def __str__(self): return self.category_name views.py The code I added to the file is as follows. def article_category(request, category_slug): categories = Category.objects.all() article = Article.objects.filter( article_status='published') if category_slug: category = get_object_or_404(Category, slug=category_slug) article = article.filter(category=category) template = 'article/category.html' context = {'article': article} return render(request, template, context) url.py url(r'^category/(?P<category_slug>[-\w]+)/$', article_category, name='article_category'), index.html The code I added to the file is as follows. <a href="{{ articles.article_category.get_absolute_url }}">{{ article.article_category }}</a> -
How to switch off Description column in Django Rest Framework Documentation?
Is it possible to switch off Description column in Django Rest Framework Documentation? As you can see on the screenshot below there is a column Description. It is obvious what username and password mean, so I don't need to add more information, however empty cells don't look well. I would like to switch off it only for this method, because for instance in others I would like to have descriptions. Any ideas how can I do this? -
Custom check_object_permissions not working in django rest framework
i am using custom permission class in django rest APIView and calling check_object_permissions explicitly in rest view but instead of my custom permission django default permission is calling how can i change it to mine or stop default one. Code views.py class StreamOptionDetails(APIView): """ Retrieve, update or delete a snippet instance. """ permission_classes = (IsOwnerOrReadOnly,) def get_object(self, pk): try: obj = Stream.objects.get(pk=pk) self.check_object_permissions(self.request, obj) return obj except Stream.DoesNotExist: raise Http404 def get_option(self, pk): try: return StreamOption.objects.get(pk=pk) except StreamOption.DoesNotExist: raise Http404 def get(self, request, stream=None, pk=None, format=None): self.get_object(stream) stream_option = self.get_option(pk) serializer = StreamOptionsSerializer(stream_option) return Response(serializer.data) error AttributeError at /streams/2/options/15/ 'StreamOption' object has no attribute 'members' Request Method: GET Request URL: http://localhost:8000/streams/2/options/15/ Django Version: 1.10 Exception Type: AttributeError Exception Value: 'StreamOption' object has no attribute 'members -
datetime display and timezone converting in django
in setting file: TIME_ZONE = 'UTC' USE_TZ = True in models: from django.utils import timezone date = models.DateTimeField(default = timezone.now()) before pip install pytz,date field in mysql db stored as UTC time, and date in front end webpage display as localtime. but after pip install pytz,date field in mysql db stored as UTC time, at the same time date in front end webpage display as UTC time too. What is the reason for this? How to do make sure that after pip install pytz,date field in mysql db stored as UTC time, and date in front end webpage display as localtime? BTW, which library is more easily done than pytz? -
Django Alluth Filling in information from oauth
Currently, I have a custom user model with the following settings ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' and an additional display name field.(non-unique) I added a signup form class to prompt users for a display name. ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.SignupForm' How do I get get allauth to automatically fill in display name(using facebook name) and email address automatically instead of prompting for the display name and email address after clicking on the facebook button? -
React+Django sending forms and recieving responses
I have django as backend and I use it also on the fronted with one exception: one big input form is made in react. After submiting the form, some calculations are made and the server returns pages of text including css, javascript (event listeners,bootstrap popovers, etc. ). The following gives me headaches: how to sumbit the form and recieve full page results in this setup? What I am currently doing when the user hits the submit button is to assemble the form data to a dict and then it goes to the server via ajax. All of this happens in the react part (see example below). If I don't send it as ajax I can not fill the error handlers in the react form. If I do send it via ajax I also need to handle the valid result via ajax. So, if there is errors, missing fields or whatever the server responds and it gets fed to the react form. If everything is okay the server sends a full html page response and I replace the whole page with it. This of course is very suboptimal and besides weird-feeling solution it also creates more technical issues, like disrupting event …